Problem 2 (Project Euler) [和訳])
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.
「C の尻尾」がとれない私は、フィボナッチ数列の第n項を返すメソッド"fibonacci"を下記の通りに書きました。
def fibonacci(n)
return nil if n < 0
pre_fibo0 = 1
pre_fibo1 = 1
i = 2
while i <= n
tmp = pre_fibo1
pre_fibo1 = pre_fibo0 + pre_fibo1
pre_fibo0 = tmp
i += 1
end
pre_fibo1
end
でも、Ruby(PerlでもPythonでも)の場合、「配列のマイナスの添え字」が有効なので定義されているので、フィボナッチ数列全体を格納する配列を用意するとすっきり書けます。
fibonacci_seq = [1, 1]
sum = 0
begin
new_term = fibonacci_seq[-1] + fibonacci_seq[-2]
fibonacci_seq << new_term
sum += new_term if new_term % 2 == 0
end while new_term < 4000000
# sumが答え…ってことで全部書いたも同然(汗
こういうのがすらすら出てこないとなぁ…。