Fibonacci sequence in Ruby (recursion)

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

    This is not the way you calculate fibonacci, you are creating huge recursive tree which will fail for relatively small ns. I suggest you do something like this:

    def fib_r(a, b, n)
      n == 0 ? a : fib_r(b, a + b, n - 1)
    end
    
    def fib(n)
      fib_r(0, 1, n)
    end
    
    p (0..100).map{ |n| fib(n) }
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-01 03:46

    We can perform list fibo series using below algorithm

    def fibo(n)
      n <= 2 ? 1 : fibo(n-1) + fibo(n-2)
    end
    

    We can generate series like below

    p (1..10).map{|x| fibo(x)}
    

    below is the output of this

    => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 
    
    0 讨论(0)
  • 2020-12-01 03:46

    fastest and smallest in lines solution:

    fiby = ->(n, prev, i, count, selfy) {
      i < count ? (selfy.call n + prev, n, i + 1, count, selfy) : (puts n)
    }
    fiby.call 0, 1, 0, 1000, fiby
    

    functional selfie pattern :)

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题