0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby】フィボナッチ数列の偶数の和を出してみた

Posted at

##はじめに
Pukiwikiで問題が難しかったので、備忘録として投稿します。

問題

フィボナッチ数列の項は前の2つの項の和である. 最初の2項を 1, 2 とすれば, 最初の10項は以下の通りである.
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
数列の項の値が20以下のとき, 値が偶数の項の総和を求めよ.
※実際の問題は400万以下の時

##解答

# フィボナッチ数列
def fib(n)
  if n <= 2
    return n
  else
    return fib(n - 2) + fib(n -1)
  end
end

array = []

20.times do |n|
  array << fib(n)
end

even_num = []

array.each do |num|
  if num % 2 == 0
    even_num << num
  end
end

puts even_num.sum

##おわりに
冗長に書きすぎている気もしますが、うまく処理が行えました!
もっと良い記述方法を思いつきましたら更新したいと思います。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?