Project Euler - Problem 2
1分間でなんてとても解けません。
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.
#!/usr/bin/env ruby def fib(n) return 0 if n < 1 return 1 if n == 1 fib(n-1) + fib(n-2) end limit = 4 * 10 ** 6 a = (1..40).inject(0) do |sum, i| result = fib(i) break sum if result > (limit) sum += result if result % 2 > 0 sum end puts a
そもそも自分のフィボナッチ数列の知識が怪しかった。
問題を読み間違えていたため、だいぶ右往左往しながらゴールという感じ。
return とか break とか無しで、もう少し奇麗に書けないものかなあ。