Help us understand the problem. What is going on with this article?

メモ化したフィボナッチ

More than 5 years have passed since last update.
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で任意のメソッドをメモ化する

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away