Problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Solve the problem using MATLAB.
Solution: To solve this problem we will use the previously created fibon.m program to generate all the even fibonacci numbers whose values are less than 4 million. We will sort out the even fibonacci numbers and finally find the sum of all the even fibonacci numbers.
If you have not seen the previous post of the fibon.m function then click here: Fibon function
If you have not seen the previous post of the fibon.m function then click here: Fibon function
The program is as follows:
%This script generates even fibonacci numbers
%Here we will use the function fibon which was created earlier
%create a vector with fibonacci numbers
fib = fibon(4000000);
%create an empty vector to store the values of eve fibonacci numbers
evenfibon = [];
%Create a for loop to loop through all the values of the fib vector
for i = 1:length(fib)
if rem(fib(i),2) == 0
evenfibon = [evenfibon fib(i)];
end
end
solution = sum(evenfibon);
fprintf('The sum of the even fibonacci numbers whose values are less than 4 million is %d\n',solution);
Download a copy of this program from here: evenfib.m
A detailed explanation with of the above problem in pdf format can be obtained from here: problem2_projecteuler_matlab.pdf
This problem is taken from projecteuler.net and can be found here: problem2.
The above code was formatted using hilite.me.
Run the program and comment below the output you are getting for a given input
Keywords: Projecteuler.net, problem2, sum of even fibonacci numbers, fibonacci numbers