Project Euler 2

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.

Solve:

clear
clc
s = 0;
a = 1;
b = 2;
while b<4000000
if mod(b,2)==0
s = s+b;
end
b = a+b;
a = b-a; %斐波那契数列,后一项等于前两项的和
end
fprintf('The answer is %.0d\n',s)

posted @ 2019-03-24 14:14  仰望灬星空  阅读(170)  评论(0编辑  收藏  举报