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】フィボナッチ数列を出力する方法

0
Last updated at Posted at 2022-11-30

フィボナッチ数列をn=10まで出力しなさい
ただしフィボナッチ数列とは
f[0] = 0
f[1] = 1
f[n] = f[n-1] + f[n-2] (n >= 2)
の数列である。

結論と解説

コード

# 空のハッシュfを作る
f = Hash.new

# 0~10の数列に対してeach文を回す
(0..10).each do |n|
  if n == 0
    f[n] = 0 # n = 0のとき、値は0
  elsif n == 1 # n = 1のとき、値は1
    f[n] = 1
  else
    f[n] = f[n-1] + f[n-2] # n >= 2のときは前項と前々項の値の和
  end
end

puts f # ハッシュの出力

出力結果

{0=>0, 1=>1, 2=>1, 3=>2, 4=>3, 5=>5, 6=>8, 7=>13, 8=>21, 9=>34, 10=>55}

おまけ

i項目の値が知りたいとき

puts f[i] # 0 < i <= n

# 例
puts f[7]
# => 13

ある値がフィボナッチ数列の何項目なのかを知りたいとき

puts f.key(val) # valはフィボナッチ数列内の値

# 例
puts f.key(55)
# => 10

日記的メモ

下の記事を書いたとき、他に有名な数列といえば、、と思いついたのがフィボナッチ数列でした。
一回作っとけば今後聞かれたときに安心ですね。

0
0
1

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?