ZeroSnake0

导航

Project Euler 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.

首两项为a与b的Fibonacci序列为

  a, b, a+b, a+2b, 2a+3b

若b为偶数,则下一偶数项为2a+3b,尝试在循环中将a与b分别前进到a+2b与2a+3b

  a' = a + 2b

  b' = 2a + 3b = 2a' - b

Python代码:

max = 4000000
sum = 0

a = 1
b = 2

while(b <= max):
    sum += b
    a += b * 2
    b = a * 2 - b
    
print sum

时间复杂度O(log(n))(Fibonacci数列通项公式为指数型)

空间复杂度O(1)

posted on 2012-12-23 10:42  ZeroSnake0  阅读(154)  评论(0)    收藏  举报