Problem2

なんか、、、
ぴえろっちが問題をくれた。その1
Rubyで解いてみたやつ
コーヒーブレイク
某さんのところで見かけた例題。
逃げ道がなくなったような気がするので、エントリーを作る。。。


本家の問題はこれ↓

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, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

日本語訳はこっち↓

フィボナッチ数列の項は前の2つの項の和である。最初の2項を 1, 2 とすれば、最初の10項は以下の通りである。

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

数列の項が400万を超えない範囲で、偶数の項の総和を求めよ。

answer,a,b = 0,1,2

while (b <= 4000000):
    b += a
    a = b - a
    if((a % 2) == 0):
        answer += a


answer
答え
4613732


これで勘弁してもらおう。。。<追記>
裏側で個人的に突っ込まれまくったので修正しました。
修正版↓

answer,a,b,limit = 0,1,2,4000000
while (a <= limit):
    if((a % 2) == 0):
        answer += a
    a,b = b,a+b

answer