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
如果n
是0
或1
和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