Fibonacci sequence in Ruby (recursion)

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

    a = [1, 1]
    while(a.length < max) do a << a.last(2).inject(:+) end
    

    This will populate a with the series. (You will have to consider the case when max < 2)

    If only the nth element is required, You could use Hash.new

    fib = Hash.new {|hsh, i| hsh[i] = fib[i-2] + fib[i-1]}.update(0 => 0, 1 => 1)
    
    fib[10]
    # => 55 
    

提交回复
热议问题