Added solution to problem 34

This commit is contained in:
2021-06-01 18:44:25 -04:00
parent caa3eda85b
commit acdb66560d

66
Problem34.lua Normal file
View File

@@ -0,0 +1,66 @@
--ProjectEuler/ProjectEulerLua/Problem34.lua
--Matthew Ellison
-- Created: 06-01-21
--Modified; 06-01-21
--Find the sum of all numbers which are equal to the sum of the factorial of their digits
--All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses
--[[
Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
]]
require "Stopwatch"
require "Algorithms"
--Setup the variables
local timer = Stopwatch:create();
local MAX_NUM = 1499999; --The largest num that can be the sum of its own digits
local numberFactorials = {}; --Holds the pre-computed factorials of the numbers 0-9
local sum = 0; --Holds the sum of all numbers equal to the sum of their digit's factorials
--Start the timer
timer:start();
--Pre-compute the possible factorials from 0! to 9!
for cnt = 0, 9 do
numberFactorials[cnt] = factorial(cnt);
end
--Run through all possible numbers from 3-MAX_NUM and see if they equal the sum of their digit's factorials
for cnt = 3, MAX_NUM do
--Split the number into its digits and add each one to the sum
local numString = tostring(cnt);
local currentSum = 0;
for numCnt = 1, string.len(numString) do
currentSum = currentSum + numberFactorials[tonumber(string.sub(numString, numCnt, numCnt))];
end
--If the number is equal to the sum add the sum to the running sum
if(currentSum == cnt) then
sum = sum + currentSum;
end
end
--Stop the timer
timer:stop();
--Print the results
io.write("The sum of all numbers that are the sum of their digit's factorials is " .. sum .. "\n");
io.write("It took " .. timer:getString() .. " to run this algorithm\n");
--[[ Results:
The sum of all numbers that are the sum of their digit's factorials is 40730
It took 1.308 seconds to run this algorithm
]]