What is a too deep stack level error? Kata code

I have this code that I'm trying to combine, but I keep getting the stack level too high:

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 have problems and I don’t understand why. Why is it too complicated. From an experienced developer. What would you say that this will be a mistake of this type? I understand that infinite recursions or something with a really large number can cause this, but what is the limit? In addition, I read from wikipedia that these errors also have something to do with the system, that your startup and the amount of memory that it can use or allocate to methods. It's true?

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

Well, it doesn't matter if my question is left out, because I really don't understand what I'm doing wrong. I also wanted to mention that I was trying 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 saw it by inserting binding.pry. I know this is a question about noob, but I just don't understand what is wrong here. Thank you guys for your patience.

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

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

-2
ruby
source share
1 answer

Your zeros function is trying to do too much. He cannot calculate the factorial and at the same time take zero zeros in it.

If you think about it when you calculate the factorial, the number of trailing zeros can (and will) change. You are only interested in the latter value. So, first calculate this and only then the number of zeros.

 # 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 
+1
source share

All Articles