Fibonacci sequence in Ruby (recursion)

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

    Try this oneliner

    def fib (n)
        n == 0 || n == 1 ? n : fib(n-2) + fib(n-1)
    end
    print fib(16)
    

    Output: 987

提交回复
热议问题