[py]
# Problem 2
# 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.
sum = 0
fib1 = 1 # first term fib_1 = 1
fib2 = 1 # second term fib_2 = 1
fib3 = fib1 + fib2 # third term fib_3 = fib_1 + fib_2
while True:
if fib3 % 2 == 0:
sum += fib3
if fib3 >= 4000000:
break
fib1 = fib2
fib2 = fib3
fib3 = fib1 + fib2
print(sum)
[/py]
[py]
4613732
[/py]
コメント
素朴にやるだけ。
改良
解答 pdf によれば、フィボナッチ数列の性質を使ってもっと効率的にできる。