Problem 2 : Even Fibonacci numbers
Problem:
Each new term in the Fibonacci sequence is generated by adding the previous two terms.By starting with1and2, 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 donot exceed four million, find the sum of the even-valued terms.
第二题与斐波那契数列相关,求所有不大于4000000的偶数斐波那契数之和。
逐一求斐波那契数,判断后决定是否累加,代码很简单:
1 #ProjectEuler promble 2: Even Fibonacci numbers 2 RANGE = 4000000 3 prev = 1 4 cur = 1 5 sum = 0 6 while cur <= 4000000: 7 if cur % 2 == 0: 8 sum += cur 9 temp = cur 10 cur += prev 11 prev = temp 12 print(sum)
结束这个问题前,再看看斐波那契数列
1 1 2 3 5 8 13 21 34 ……
a b c a b c a b c ……
可见,斐波那契数列偶数项的分布是有规律的,这样可以省略判断是否为偶数的步骤:
1 #ProjectEuler promble 2: Even Fibonacci numbers 2 RANGE = 4000000 3 odd1 = 1 4 odd2 = 1 5 even = odd1 + odd2 6 sum = 0 7 while even <= 4000000: 8 sum += even 9 odd1 = odd2 + even 10 odd2 = even + odd1 11 even = odd1 + odd2 12 13 print(sum)
本题结束。