Fibonacci sequence in Ruby (recursion)

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

    Here is a more concise solution that builds a lookup table:

    fibonacci = Hash.new do |hash, key|
      if key <= 1
        hash[key] = key
      else
        hash[key] = hash[key - 1] + hash[key - 2]
      end
    end
    
    fibonacci[10]
    # => 55 
    fibonacci
    # => {1=>1, 0=>0, 2=>1, 3=>2, 4=>3, 5=>5, 6=>8, 7=>13, 8=>21, 9=>34, 10=>55}
    

提交回复
热议问题