Files
ProjectEulerOctave/Problem2.m
2020-10-30 16:19:30 -04:00

58 lines
1.7 KiB
Matlab

function [] = Problem2()
%ProjectEuler/Octave/Problem2.m
%Matthew Ellison
% Created: 03-28-19
%Modified: 10-28-20
%The sum of the even Fibonacci numbers less than 4,000,000
%{
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/>.
%}
%Setup your Variables
fib = [1, 1, 2]; %Holds the Fibonacci numbers
currentFib = fib(end) + fib(end - 1); %The current Fibonacci number to be tested
evenFib = [2]; %A subset of the even Fibonacci numbers
%Start the timer
startTime = clock();
while(currentFib < 4000000)
%Add the number to the list
fib(end + 1) = currentFib;
%If the number is even add it to the even list as well
if(mod(currentFib, 2) == 0)
evenFib(end + 1) = currentFib;
end
%Set the next Fibonacci
currentFib = fib(end) + fib(end - 1);
end
%Stop the timer
endTime = clock();
%Print the results
printf("The sum of all even Fibonacci numbers less than 4000000 is %d\n", sum(evenFib))
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
end
%{
Results:
The sum of all even Fibonacci numbers less than 4000000 is 4613732
It took 0.000694 seconds to run this algorithm
%}