1
2

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

単純な再帰で書く

絶対おそい(nが0or1の深さになるまで再帰するため)。

def fib(n)
    return n if n == 0 || n == 1
    return fib(n - 1) + fib(n - 2)
end

ちょっと工夫した再帰

再帰だが、やってることはfor文と大して変わらない。
ただ再帰関数なので、超でかいnが渡されたらスタックオーバーフローするかも?

def fib(n, a, b)
    return a if n == 0
    return fib(n - 1, b, a + b)
end

forで書く

再帰じゃないのでスタックオーバーフローが発生しない…はず。
分割代入使うとキレイに書ける。
分割代入をすこれ。

def fib(n)
    a, b = 0, 1
    n.times.each { a, b = b, a + b }
    a
end

動的計画法(メモ化)で書く

TODO 誰か書いてください。

1
2
5

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?