LoginSignup
3
3

More than 5 years have passed since last update.

メモ化したフィボナッチ

Last updated at Posted at 2013-01-02
fib.rb
#ふつうのフィボナッチ
def fib(n)
  (0..1).include?(n)? n : fib(n-2) + fib(n-1)
end

#メモ化したフィボナッチ
def cash_fib(n) 
  @cash ||= []
  @cash[n] ||= (0..1).include?(n)? n : cash_fib(n-2) + cash_fib(n-1)
end

#一瞬で計算が終わる
print cash_fib 1000
# => 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875

参考
Rubyで任意のメソッドをメモ化する

3
3
0

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
3
3