Problem 2:Even Fibonacci numbers

原题地址:http://projecteuler.net/problem=2

Even Fibonacci numbers

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.


大意是:

斐波那契数列中的每一项被定义为前两项之和。从1和2开始,斐波那契数列的前十项为:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

考虑斐波那契数列中数值不超过4百万的项,找出这些项中值为偶数的项之和。


解法1:

从1遍历到4百万,如果斐波那契数列中某项是偶数,则累加起来。

python代码如下:

i = 1
j = 2
n = 2
sum = 0
max = 4E6
while n < max:
    if n%2 ==0:
        sum+=n
    n = i + j
    i = j
    j = n
    
print sum




注:题目的中文翻译源自http://pe.spiritzhang.com

你可能感兴趣的:(python,projecteuler)