您的位置:首页 > 其它

Project Euler Problem 2 - Even Fibonacci numbers

2012-12-23 10:42 381 查看

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: