mirror of
https://bitbucket.org/Mattrixwv/projecteulerlua.git
synced 2025-12-06 09:33:58 -05:00
63 lines
2.1 KiB
Lua
63 lines
2.1 KiB
Lua
--ProjectEuler/lua/Problem20.lua
|
|
--Matthew Ellison
|
|
-- Created: 03-14-19
|
|
--Modified: 06-19-20
|
|
--What is the sum of the digits of 100!
|
|
--All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses
|
|
--I used the bigint library from https://github.com/empyreuma/bigint.lua
|
|
--[[
|
|
Copyright (C) 2020 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"
|
|
local bigint = require("bigint")
|
|
|
|
TOP_NUM = 100;
|
|
|
|
|
|
--Start the timer
|
|
local timer = Stopwatch:create();
|
|
timer:start();
|
|
|
|
local num = bigint.new(1); --The number to be generated
|
|
local sum = 0; --The sum of the digits in num
|
|
|
|
for cnt = 1, TOP_NUM do
|
|
num = bigint.multiply(num, bigint.new(cnt));
|
|
end
|
|
|
|
--Get a string of the number because it is easier to pull appart the individual characters to get the sum
|
|
local numString = bigint.unserialize(num, 's');
|
|
--Run through every character in the string, convert it back to an integer and add it to the running sum
|
|
for cnt = 1, string.len(numString) do
|
|
sum = sum + tonumber(string.sub(numString, cnt, cnt));
|
|
end
|
|
|
|
--Stop the timer
|
|
timer:stop()
|
|
|
|
--Print the results
|
|
io.write("100! = " .. numString .. '\n');
|
|
io.write("The sum of the digits is: " .. sum .. '\n');
|
|
io.write("It took " .. timer:getMilliseconds() .. " milliseconds to run this algorithm\n");
|
|
|
|
--[[ Results:
|
|
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
|
|
The sum of the digits is: 648
|
|
It took 81.113 milliseconds to run this algorithm
|
|
]]
|