とんちゃんといっしょ

Cloudに関する技術とか日常とかについて書いたり書かなかったり

Problem 2

問題

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

英語

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.

http://projecteuler.net/index.php?section=problems&id=2
日本語

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

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

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

Note:この問題は最近更新されました。お使いのパラメータが正しいかどうか確認してください。

http://odz.sakura.ne.jp/projecteuler/index.php?Problem%202

解説

問題をそのまま実装。
フィボナッチ数列をHashで実装してるあたりが特殊だと思う。

ソースコード(Ruby)

fib = Hash.new{|h,k|h[k] = h[k-1] + h[k-2]}
fib[0], fib[1] = 1, 2
i, sum = 0, 0
while fib[i] < 4e6
    sum += fib[i] if fib[i] % 2 == 0
    i+=1
end
p sum