Files
ProjectEulerLua/Problem2.lua

60 lines
2.1 KiB
Lua

--ProjectEuler/lua/Problem1.lua
--Matthew Ellison
-- Created: 02-01-19
--Modified: 06-19-20
--The sum of the even Fibonacci numbers less than 4,000,000
--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"
local timer = Stopwatch:create();
timer:start();
--Setup the variables
TOP_NUM = 4000000; --The highest looked for Fibonacci numbers
local fibSum = 0; --Holds the sum of the Fibonacci numbers
local fibNums = {1, 1, 2}; --An array to keep track of the Fibonacci numbers
--Loop to generate the Fibonacci numbers
local cnt = 2; --A counter to hold the location in the array of the currently working Fibonacci number
fibNums[(cnt % 3) + 1] = fibNums[((cnt - 1) % 3) + 1] + fibNums[((cnt - 2) % 3) + 1];
while(fibNums[(cnt % 3) + 1] < TOP_NUM) do
--If the number is even add it to the sum, otherwise ignore it
if((fibNums[(cnt % 3) + 1] % 2) == 0) then
fibSum = fibSum + fibNums[(cnt % 3) + 1];
end
--Generate the next Fibonacci number in the sequence
cnt = cnt + 1
fibNums[(cnt % 3) + 1] = fibNums[((cnt - 1) % 3) + 1] + fibNums[((cnt - 2) % 3) + 1];
end
timer:stop();
--Print the results
print("The sum of all even Fibonacci numbers less than " .. TOP_NUM .. " is " .. fibSum);
print("It took " .. timer:getMicroseconds() .. " microseconds to run this algorithm");
--[[Results:
The sum of all even Fibonacci numbers less than 4000000 is 4613732
It took 56 microseconds to run this algorithm
]]