Project Euler_Problem 2:Even Fibonacci numbers(MATLAB)
Problem 2
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.
a=[1 2];%初始化a向量
%求不超过4,000,000的Fibonacci数是第几项
for i=3:100
a(i) = a(i -1) + a(i - 2);
disp(a(i));
if(a(i) > 4000000)
I=i-1;
break;
end
end
disp(I);
s = 0; %初始化和s=0
%求出偶数值项的和
for i = 1:I
if mod(a(i),2)==0 %判断是否为偶数
s = s + a(i);
fprintf('a(%d)=%d\n',i,a(i));
fprintf('s=%d\n',s);
end
end
disp(s);%输出s
要注意题中的even-valued terms 的意思是为偶数值的项,而不是偶数项。