Given an integer n, write a Go program to count the number of trailing zeros in the factorial of n.
Input : 7 Output : 1 Explanation: 7! = 5040, which has 1 trailing zero Input : 10 Output : 2 Explanation: 10! = 3628800, which has 2 trailing zeros
Naive approach: To count the trailing zeros in n!, one approach is to find the factorial of n and then count the number of trailing zeros using a loop and counting the number of (n%10==0)s. However, even for small numbers such as 20, the factorial value is large enough to cause integer overflow.
Efficient Approach: To count the number of trailing zeros, it is first required to understand what contributes trailing zeros in the factorial of a number.
The number 10 is responsible for the trailing zeros. The prime factorization of 10 is 2*5. In prime factorization of any number, the number of 2s is always greater than or equal to the number of 5s. Hence, it is only required to find the number of fives in the prime factorization of the number.
Example 1: When n = 7, the prime factorization of 7! is 2^4 * 3^2 * 5^1 * 7^1. The number of 5s in the prime factorization is 1. Hence, the number of trailing zeros in 7! is 1.
Example 2: When n = 10, the prime factorization of 10! is 2^8 * 3^4 * 5^2 * 7^1. The number of 5s in the prime factorization is 2. Hence, the number of trailing zeros in 10! is 2.
trailingZerosCount = floor(n/5) + floor(n/5^2) + floor(n/5^3) + …. + floor(n/5^k) where 5^k <= n
The number of trailing zeros in 10! is 2
- Count trailing zeroes in factorial of a number
- Find the smallest number X such that X! contains at least Y trailing zeros.
- Number of trailing zeros in N * (N - 2) * (N - 4)*....
- Smallest number with at least n trailing zeroes in factorial
- Find the last digit when factorial of A divides factorial of B
- Trailing number of 0s in product of two factorials
- Number of trailing zeroes in base 16 representation of N!
- Number of trailing zeroes in base B representation of N!
- Program for factorial of a number
- C Program for factorial of a number
- Java Program for factorial of a number
- Python Program for factorial of a number
- Count numbers having N 0's and and M 1's with no leading zeros
- How to print console without trailing newline in Node.js ?
- Check if a given number is factorial of any number
- Count digits in a factorial | Set 2
- Count factorial numbers in a given range
- Count digits in a factorial | Set 1
- Count Divisors of Factorial
- Format a number with leading zeros in PHP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : TanmayThaakur