[Solved] What constitutes a stack level too deep error? Code Kata


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

6

solved What constitutes a stack level too deep error? Code Kata