# Math Help - matlab code asap thanks Fibonacci sequence

1. ## matlab code asap thanks Fibonacci sequence

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, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.

what is the matlab code

I have no idea what to do i got this so far and i do not know if its right???

f=zeros(1,4000000);
f(1)=1;
f(2)=1;
for j= 3:4000000
f(j)=f(j-1)+f(j-2);
end
sum(f<4000000)

2. Originally Posted by savni98
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, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.

what is the matlab code

I have no idea what to do i got this so far and i do not know if its right???

f=zeros(1,4000000);
f(1)=1;
f(2)=1;
for j= 3:4000000
f(j)=f(j-1)+f(j-2);
end
sum(f<4000000)
First you are generating the numbers from the wrong starting point, you are told to use f(1)=1, f(2)=2, but no matter it works better starting with f(1)=1, f(2)=1.

You don't need to store the numbers, and you have to sum every third one, the following may work (its untested):

Code:
a=1;b=1;

sum=0;                %running total of the even Fib. numbers
for idx=3:4000000     %loop over a sufficient range no get a Fib. number over 4000000
n=a+b;              %next Fib number
a=b;b=n;            %reset last two numbers for next trip arround loop
if n>4000000        %exit loop if current number >4000000
break
end
if mod(idx,3)==0    %if this is an even Fib number add so running total
sum=sum+n;
end
end
CB