文章目錄

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

Even Fibonacci numbers

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,。。。

考虑斐波那契数中不超过4000000的数,求这些数中所有偶数的和。

解法:

这题不多说,关键是生成斐波那契数列,这里使用了一个迭代器的技巧。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
Created on 2013-4-26

@author: shilong
@email: long470884130@163.com
'''


def fibonacci():
"""一个迭代函数,每次得到一个斐波那契数,依次将得到1, 2, 3, 5..."""
a = 1
b = 1
while True:
yield a
a, b = a + b, a

if __name__ == "__main__":
fi = fibonacci()
s = 0
while True:
n = next(fi)
if n >= 4000000:
break
if n % 2 == 0:
s += n
print s

打赏作者

文章目錄