mirror of
https://bitbucket.org/Mattrixwv/projecteulerlua.git
synced 2025-12-06 09:33:58 -05:00
67 lines
2.3 KiB
Lua
67 lines
2.3 KiB
Lua
--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
|
|
]]
|