Fibonacci sequence in Ruby (recursion)

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

    Joining the Fibonacci train:

    Regular:

    def fib(num)
      return num if (num < 2) else fib(num-1) + fib(num-2)
    end
    

    With caching:

    module Fib
      @fibs = [0,1]
      def self.calc(num)
        return num if (num < 2) else @fibs[num] ||= self.calc(num-1) + self.calc(num-2)
      end
    end
    

提交回复
热议问题