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..
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??
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. 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。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.