Fibonacci sequence in Ruby (recursion)

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

    Linear

    module Fib
      def self.compute(index)
        first, second = 0, 1
        index.times do
          first, second = second, first + second
        end
        first
      end
    end
    

    Recursive with caching

    module Fib
      @@mem = {}
      def self.compute(index)
        return index if index <= 1
    
        @@mem[index] ||= compute(index-1) + compute(index-2)
      end
    end
    

    Closure

    module Fib
      def self.compute(index)
        f = fibonacci
        index.times { f.call }
        f.call
      end
    
      def self.fibonacci
        first, second = 1, 0
        Proc.new {
          first, second = second, first + second
          first
        }
      end
    end
    

    None of these solutions will crash your system if you call Fib.compute(256)

提交回复
热议问题