简体   繁体   English

Ruby递归不起作用?

[英]Ruby Recursion doesn't work?

I was trying to make a recursive algorithm with Ruby and I couldn't do it so I kept popping the stack as it were and each time I tried a simpler recursive algorithm to see where my mistake was.. 我试图用Ruby创建递归算法,但是我做不到,所以我一直按原样弹出堆栈 ,每次尝试使用更简单的递归算法来查看错误所在时。

But I arrived at this: 但是我到达了这里:

def fact(n)
  if n==0
    1
  else
    fact(n)*fact(n-1)  
  end
end

puts fact(5)

and

ruby/part2.rb:81: stack level too deep (SystemStackError)

Ok what is going on? 好的,这是怎么回事?

Is it not possible to make recursive algorithms in Ruby?? 不能在Ruby中创建递归算法吗?

your algorithm is incorrect, it should look like this 您的算法不正确,应该看起来像这样

def fact(n)
  if n==0
    1
  else
   n*fact(n-1)  
  end
end

puts fact(5)

fact(n) * fact(n - 1) is infinite recursion. fact(n) * fact(n - 1)是无限递归。 You need to reduce the problem size in each call. 您需要减少每个呼叫中​​的问题大小。

def fact(n)
  if n <= 0
    1
  else
    n * fact(n - 1)  
  end
end

Or simply, 或者简单地说,

def fact(n)
  n <= 0 ? 1 : n * fact(n - 1)  
end

您必须执行诸如fact(n-1)* fact(n-2)之类的操作,因为否则,将永远调用fact(n),n = 5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM