Project Euler 2

Project Euler 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, \dots\]

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

解决方案

直接依照递推式\(F(i)=F(i-1)+F(i-2)\)进行递推即可,时间复杂度为对数级别。

代码

1
2
3
4
5
6
7
8
9
10
11
N = 4 * 10 ** 6
a, b = 1, 2
ans = 0
while True:
if a > N:
break
if a % 2 == 0:
ans += a
c = a + b
a, b = b, c
print(ans)
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
Ujimatsu Chiya 微信 微信
Ujimatsu Chiya 支付宝 支付宝