mirror of
https://bitbucket.org/Mattrixwv/projecteulerlua.git
synced 2025-12-06 09:33:58 -05:00
92 lines
2.3 KiB
Lua
92 lines
2.3 KiB
Lua
--ProjectEuler/lua/Problem23.lua
|
|
--Matthew Ellison
|
|
-- Created: 03-22-19
|
|
--Modified: 06-19-20
|
|
--Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers
|
|
--All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses
|
|
--[[
|
|
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"
|
|
require "Algorithms"
|
|
|
|
|
|
MAX_NUM = 28123; --The highest number that will be evaluated
|
|
|
|
|
|
local function isSum(abund, num)
|
|
local sumOfNums = 0;
|
|
--Pick a number for the first part of the sum
|
|
for firstNum = 1, #abund do
|
|
for secondNum = firstNum, #abund do
|
|
sumOfNums = abund[firstNum] + abund[secondNum];
|
|
if(sumOfNums == num) then
|
|
return true;
|
|
elseif(sumOfNums > num) then
|
|
break;
|
|
end
|
|
end
|
|
end
|
|
return false;
|
|
end
|
|
|
|
|
|
--Setup the variables
|
|
local timer = Stopwatch:create();
|
|
local divisorSums = {};
|
|
|
|
--Start the timer
|
|
timer:start();
|
|
|
|
--Get the sum of the divisors of all numbers < MAX_NUM
|
|
for cnt = 1, MAX_NUM do
|
|
local div = getDivisors(cnt);
|
|
if(#div > 1) then
|
|
table.remove(div, #div);
|
|
end
|
|
divisorSums[cnt] = getSum(div);
|
|
end
|
|
|
|
--Get the abundant numbers
|
|
local abund = {};
|
|
for cnt = 1, #divisorSums do
|
|
if(divisorSums[cnt] > cnt) then
|
|
abund[#abund + 1] = cnt;
|
|
end
|
|
end
|
|
|
|
--Check if each number can be the sum of 2 abundant numbers and add to the sum if no
|
|
local sumOfNums = 0;
|
|
for cnt = 1, MAX_NUM do
|
|
if(not isSum(abund, cnt)) then
|
|
sumOfNums = sumOfNums + cnt;
|
|
end
|
|
end
|
|
|
|
--Stop the timer
|
|
timer:stop();
|
|
|
|
--Print the results
|
|
io.write("The answer is " .. sumOfNums .. '\n');
|
|
io.write("It took " .. timer:getSeconds() .. " seconds to run this algorithm\n");
|
|
|
|
--[[Results:
|
|
The answer is 4179871
|
|
It took 393.139 seconds to run this algorithm
|
|
]]
|