Project Eulerの問題をMatlabで解いてみる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.
400万以下のフィボナッチ数のうち、偶数のものの和を求めよ。
汚いやり方かもしれないけど、以下のように作ってみた。
mx = 4000000; A = [1 2]; k = 3; while A(k-1) + A(k-2) < mx A(k) = A(k-1) + A(k-2); k = k+1; end disp(sum(A(mod(A,2)==0)));
フィボナッチ数列の最初の2つは1と2で決めうち。次のフィボナッチ数が400万未満だったら、その数字を(行列を拡張しつつ)代入していく。最後に偶数だけを選び出して和をとって表示。