Fibonacci sequence in Ruby (recursion)

后端 未结 24 1245
悲&欢浪女
悲&欢浪女 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:46

    We can perform list fibo series using below algorithm

    def fibo(n)
      n <= 2 ? 1 : fibo(n-1) + fibo(n-2)
    end
    

    We can generate series like below

    p (1..10).map{|x| fibo(x)}
    

    below is the output of this

    => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 
    

提交回复
热议问题