Fibonacci sequence in Ruby (recursion)

后端 未结 24 1284
悲&欢浪女
悲&欢浪女 2020-12-01 02:54

I\'m trying to implement the following function, but it keeps giving me the stack level too deep (SystemStackError) error.

Any ideas what the problem mi

24条回答
  •  旧时难觅i
    2020-12-01 03:54

    yet another ;)

    def fib(n)
      f = Math.sqrt(5)
      ((((1+f)/2)**n - ((1-f)/2)**n)/f).to_i
    end
    

    will be convenient to add some caching as well

    def fibonacci
      @fibonacci ||= Hash.new {|h,k| h[k] = fib k }
    end
    

    so we'll be able to get it like

    fibonacci[3]  #=> 2
    fibonacci[10] #=> 55
    fibonacci[40] #=> 102334155
    fibonacci     #=> {3=>2, 10=>55, 40=>102334155}
    

提交回复
热议问题