problem2:
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.
代码的关键是在while中嵌套循环,对斐波那契数列中的偶数进行相加。
MATLAB代码如下:
sum=0;
n1=1;
n2=2;
while(n2<4000000)
if rem(n2,2)==0
sum=sum+n2;
end
n2=n1+n2;
n1=n2-n1;
end
sum
最终答案为:4613732