mirror of
https://bitbucket.org/Mattrixwv/projecteulerlua.git
synced 2025-12-06 17:43:57 -05:00
66 lines
2.1 KiB
Lua
66 lines
2.1 KiB
Lua
--ProjectEUler/lua/Problem12.lua
|
|
--Matthew Ellison
|
|
-- Created: 02-07-19
|
|
--Modified: 06-19-20
|
|
--What is the value of the first triangle number to have over five hundred divisors?
|
|
--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"
|
|
|
|
|
|
local timer = Stopwatch:create();
|
|
timer:start();
|
|
|
|
GOAL_DIVISORS = 500;
|
|
|
|
local triangularNumber = 1;
|
|
local nextNumber = 2;
|
|
local foundNumber = false;
|
|
local divisors = {};
|
|
|
|
while((not foundNumber) and (triangularNumber > 0)) do
|
|
--See how many divisors this triangular number has
|
|
divisors = getDivisors(triangularNumber);
|
|
--If it has more than GOAL_DIVISORS raise a flag to stop the loop
|
|
if(#divisors > GOAL_DIVISORS) then
|
|
foundNumber = true;
|
|
else
|
|
triangularNumber = triangularNumber + nextNumber; --Add the next number to continue the triangular sequence
|
|
nextNumber = nextNumber + 1; --Advance to the next number for the triangular sequence
|
|
end
|
|
end
|
|
|
|
timer:stop();
|
|
|
|
--Print the results
|
|
if(foundNumber) then
|
|
print("The first triangular number with more than " .. GOAL_DIVISORS .. " divisors is " .. triangularNumber);
|
|
else
|
|
print("There was an error. Could not find a triangular number with " .. GOAL_DIVISORS .. " divisors before overflow");
|
|
end
|
|
print("It took " .. timer:getSeconds() .. " seconds to run this algorithm");
|
|
|
|
|
|
--[[Results
|
|
The first triangular number with more than 500divisors is 76576500
|
|
It took 1.498547 seconds to run this algorithm
|
|
]]
|