Skip to content
Advertisement

why is there a stack overflow error in a recursive solution to finding the factorials of a number?

I’m solving LeetCode #172:

Given an integer n, return the number of trailing zeroes in n!

Constraints:

  • 0 <= n <= 104

My code finds the answer of n! first and then counts the number of trailing zeroes. However, running the code throws a stack overflow exception, and I can’t for the life of me figure out why.

This is the code:

JavaScript

Advertisement

Answer

You said:

Given an integer n, return the number of trailing zeroes in n!

Constraints:

  • 0 <= n <= 104

First, your solution won’t work because an int can’t hold that large a number. You need to use BigInteger as shown below.

The following recursive form will compute 104! without much noticeable delay.

JavaScript

prints

JavaScript

But you don’t need to compute the factorial to solve the actual problem. Consider the following.

The product of all the numbers from 1 to N must have divisors of 10 (i.e. 2 and 5). 5 will occur the least number of times so that is where you need to focus. The number of trailing zeros is equal to the number of times that 10 divides N. And since 5 may divide a given term more than once (e.g. 25, and 125) you need to update the divisor as well.

JavaScript

prints

JavaScript

And here is the recursive solution (although not as efficient).

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement