Fibonacci sequence in Ruby (recursion)

后端 未结 24 1270
悲&欢浪女
悲&欢浪女 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条回答
  •  孤城傲影
    2020-12-01 03:43

    This is not the way you calculate fibonacci, you are creating huge recursive tree which will fail for relatively small ns. I suggest you do something like this:

    def fib_r(a, b, n)
      n == 0 ? a : fib_r(b, a + b, n - 1)
    end
    
    def fib(n)
      fib_r(0, 1, n)
    end
    
    p (0..100).map{ |n| fib(n) }
    

提交回复
热议问题