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)
相关文章推荐
- Project Euler Problem 2: Even Fibonacci numbers
- (Problem 2)Even Fibonacci numbers
- Project Euler Problem 25 :1000-digit Fibonacci number
- Project Euler Problem 387 - Harshad Numbers - 深度优先
- 【Project Euler】【Problem 2】Even Fibonacci numbers
- (Problem 2)Even Fibonacci numbers
- (Problem 2)Even Fibonacci numbers
- Project Euler Problem 104 Pandigital Fibonacci ends
- [欧拉计划]Problem 2.Even Fibonacci numbers
- Problem 2 : Even Fibonacci numbers
- Project Euler Problem 25 1000-digit Fibonacci number
- Problem 2 Even Fibonacci numbers
- Problem 2 Even Fibonacci numbers (fibonacci 数学规律)
- Problem 2:Even Fibonacci numbers
- Project Euler Problem 543 Prime-Sum Numbers
- Matlab 编程 Project Euler Problem 21 Amicable numbers
- project euler problem 25 大数连加Fibonacci序列
- Maximum path sum I [Project Euler.Problem 18]
- Project Euler problem 7
- Project Euler problem 17