Project Euler 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, ... 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万を超えないようなフィボナッチ数列の偶数項の合計を求めなさい。
Mathematica
A = 0; For[i = 2, Fibonacci[i] <= 4000000, i++, A += If[EvenQ[Fibonacci[i]], Fibonacci[i], 0]; ] A
何が400万なのか最初よく分からず変に苦労しました。
初めて習ったプログラミング言語がCなので、どうしてもそういう書き方になってしまいますね。
別解1
Module[ {a = 1, b = 2, c = 2, sum = 2}, While[a + b <= 4000000, c = a + b; If[EvenQ[c], sum = sum + c]; a = b; b = c; ]; sum ]
別解2
Total@Select[Fibonacci@Range[30], EvenQ]
なんと1行の解答。
C/C++
#include <iostream> using namespace std; int fibonacci(int); int main(){ int ans = 0; int tmp; for(int i=1 ; i<1000 ; i++){ tmp = fibonacci(i); if(tmp > 4000000) break; if(tmp%2 == 0) ans += tmp; } cout << ans << endl; return 0; } /* n 番目のフィボナッチ数を返す。 0番目→1, 1番目→1とする。 */ int fibonacci(int n){ if(n>1) return fibonacci(n-1)+fibonacci(n-2); else return 1; }
フィボナッチ数の作り方をど忘れしてて焦った。