Ruby中的斐波那契序列(递归) [英] Fibonacci sequence in Ruby (recursion)

查看:67
本文介绍了Ruby中的斐波那契序列(递归)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现以下功能,但是它一直给我stack level too deep (SystemStackError)错误.

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 might be ?

def fibonacci( n )
    [ n ] if ( 0..1 ).include? n
    ( fibonacci( n - 1 ) + fibonacci( n - 2 ) ) if n > 1
end

puts fibonacci( 5 )

推荐答案

尝试一下

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

也请查看此帖子斐波那契单衬线

以及更多.. 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

如果n01

add最后两个数字不是last和next

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

一支班轮

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

这篇关于Ruby中的斐波那契序列(递归)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆