Fibonacci sequence in Ruby (recursion)

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

    Try this

    def fibonacci( n )
      return  n  if ( 0..1 ).include? n
      ( fibonacci( n - 1 ) + fibonacci( n - 2 ) )
    end
    puts fibonacci( 5 )
    # => 5
    

    check this post too Fibonacci One-Liner

    and more .. https://web.archive.org/web/20120427224512/http://en.literateprograms.org/Fibonacci_numbers_(Ruby)

    You have now been bombarded with many solutions :)

    regarding problem in ur solution

    you should return n if its 0 or 1

    and add last two numbers not last and next

    New Modified version

    def fibonacci( n )
        return  n  if n <= 1 
        fibonacci( n - 1 ) + fibonacci( n - 2 )
    end 
    puts fibonacci( 10 )
    # => 55
    

    One liner

    def fibonacci(n)
       n <= 1 ? n :  fibonacci( n - 1 ) + fibonacci( n - 2 ) 
    end
    puts fibonacci( 10 )
    # => 55
    

提交回复
热议问题