Updated problem 1 algorithm

This commit is contained in:
2020-10-26 14:44:44 -04:00
parent 55dc150d62
commit a205fbfd0c

View File

@@ -1,7 +1,7 @@
--ProjectEuler/lua/Problem1.lua --ProjectEuler/lua/Problem1.lua
--Matthew Ellison --Matthew Ellison
-- Created: 02-01-19 -- Created: 02-01-19
--Modified: 06-19-20 --Modified: 10-26-20
--What is the sum of all the multiples of 3 or 5 that are less than 1000 --What is the sum of all the multiples of 3 or 5 that are less than 1000
--All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses --All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses
--[[ --[[
@@ -25,19 +25,23 @@
require "Stopwatch" require "Stopwatch"
local TOP_NUMBER = 999; --This is the largest number that you are going to check
local sumOfMultiples = 0;
local timer = Stopwatch:create(); local timer = Stopwatch:create();
timer:start(); timer:start();
local TOP_NUMBER = 999; --This is the largest number that you are going to check --Gets the sum of the progression of the multiple
local sumOfMultiples = 0; local function sumOfProgression(multiple)
for num = 1, TOP_NUMBER do local numTerms = TOP_NUMBER // multiple; --This gets the number of multiples of a particular number that is < MAX_NUMBER
if((num % 3) == 0) then --The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term
sumOfMultiples = sumOfMultiples + num; return ((numTerms / 2) * (multiple + (numTerms * multiple)));
elseif((num % 5) == 0) then
sumOfMultiples = sumOfMultiples + num;
end
end end
--Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
sumOfMultiples = math.floor(sumOfProgression(3)) + math.floor(sumOfProgression(5)) - math.floor(sumOfProgression(3 * 5));
timer:stop() timer:stop()
--Print the results --Print the results
@@ -47,5 +51,5 @@ print("It took " .. timer:getMicroseconds() .. " microseconds to run this algori
--[[Results: --[[Results:
The sum of all numbers < 1000 is 233168 The sum of all numbers < 1000 is 233168
It took 148 microseconds to run this algorithm It took 2.0 microseconds to run this algorithm
]] ]]