Published in

Javarevisited

Examples :

`Input: n = 5Output: 1Factorial of 5 is 120 which has one trailing 0.Input: n = 20Output: 4Factorial of 20 is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 which has 4 trailing zeroes.Input: n = 100Output: 24Factorial of 20 is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 which has 24 trailing zeroes.`

Algorithm

1. Find the factorial of the given number using the carry-over approach.
2. Initialize a count variable as 0.
3. Use reverse for loop to check if the number is 0 or not by taking a mod of it with 10.
4. If the number is zero, increase the count by 1.
5. Print this count.

Efficient Approach

`Input: n = 5Prime Factors — 2x2x2x3x5Output: 1 — we have only 1 factor of 5Factorial of 5 is 120 which has only 1 trailing zero.Input: n = 11Prime Factors — 28x34x52x7Output: 2–2 factors of 5Factorial of 20 is 39916800 which has 2 trailing zeroes.`

Algorithm

1. Initialize the count variable as 0
2. Use a for loop to divide the number by a power of 5–5, 25, 125, etc
3. If the result of the division is greater than 1, increase the value of the count by that number.
4. Print or return count as this will be our answer or the number of trailing zeros

Output

--

--

More from Javarevisited

A humble place to learn Java and Programming better.

Get the Medium app

I am a front-end developer from India with over one year of experience in freelancing with skills like Git, HTML5, CSS3, Bootstrap 4&5, and React.