Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

ruby - What constitutes a stack level too deep error? Code Kata

I have this code which I am trying to combine but I keep getting a stack level too deep error:

def zeros(n)
  trailing_zeros(n) if n == 1
  zeros(n-1) * n
end

def trailing_zeros(number)
 sort_sum = number.to_s.split(//).reverse
 counter = 0
 until sort_sum[counter] != "0"
  counter += 1
 end
 counter
end

puts zeros(5)

Individually, they work fine, but when I try to combine them, I run into problems and I don't understand why. Why does this constitute as a stack level too deep. From an experienced developer. What would cue you off that this would be an error of that type? I understand that infinite recursions or something with a really big number could cause it but what's the limit? Also, I read from wikipedia, that these type of errors also have something to do with the system that your running and the amount of memory it can use or allocate to the methods. Is this true?

-------EDIT---------

Well, it doesn't matter if my question gets downvoted because I really don't understand what I'm doing wrong. I also wanted to mention that I did try to use return trailing_zeros(n) as you guys mentioned.

def zeros(n)
  return trailing_zeros(n) if n == 1
  zeros(n-1) * n
end

The only problem with this is that I get a value of 0. I've seen it by inserting a binding.pry. I know this is a noob question but I just don't see what is wrong here. Thanks guys for your patience.

-------EDIT------

To clarify, I'm trying to get the trailing zeros of a factorial. If I pass in 5, I will get 1 #120. If I pass a 12, I will get 2 #479001600

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your zeros function is trying to do too much. It can't calculate a factorial and at the same time count trailing zeroes in it.

If you think about it, while you are calculating the factorial, number of trailing zeroes may (and will) change. You're only interested in the final value. So first calculate that and only then count zeroes.

# inefficient(!) recursive calculation of factorial
# for more efficiency use loop
def factorial(n)
  raise "only positive values are allowed" if n < 0

  return 1 if n == 0
  n * factorial(n - 1)
end

def zeros(n)
  trailing_zeros(factorial(n))
end

def trailing_zeros(number)
 sort_sum = number.to_s.split(//).reverse
 counter = 0
 until sort_sum[counter] != "0"
  counter += 1
 end
 counter
end

zeros(5) # => 1
zeros(12) # => 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...