Problem 2
- 2010年 1月 22日
- 投稿者 : rei
Original
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項は以下の通りである。
数列の項が400万を超えない範囲で、偶数の項の総和を求めよ。
当てにならないソースコード(C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; namespace ProjectEuler { class Problem2 { const int max = 4000000; public Problem2() { int a = 1, b = 2, c, sum = 2; Console.WriteLine(this.ToString()); for (int i = 3; ; i++) { c = ((i & 1) == 0) ? (b += a) : (a += b); if ((c & 1) == 0) if (c >= max) break; sum += c; } Console.WriteLine("> " + sum); } } } |
連続した2項が分かれば次の項が分かるので、
変数a,bをその2項とし、交互に更新してます。
当てにならないソースコード(F#)
1 2 3 4 5 6 7 8 9 10 | let problem2 () = let rec _fib a b limit = match a > limit with | true -> [] | false -> a::(_fib b (a+b) limit) let fib limit = _fib 1 2 limit (fib 4000000) |> List.filter (fun n -> n &&& 1 = 0) |> List.sum |> printfn "Problem 2 > %d" |
fib は limit 以下のフィボナッチ数のリストを取得する関数です。
コメントはまだありません。