进阶之路

导航

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.

 

#斐波那契数列,python有个简易写法
s = 0  # 求和
a, b = 1, 1  # 赋初始值
n = 4000000  # 最大数
while True:
    a, b = b, a+b 
    if b >= n:
        break
    if b % 2 == 0:  # 满足偶数项条件
        s += b
print(s)

%time %run ol002.py
4613732
Wall time: 2 ms

 

posted on 2017-11-27 14:21  中年小Q  阅读(125)  评论(0编辑  收藏  举报