![]() |
VOOZH | about |
Your task is to calculate the number of trailing zeros in the factorial N!.
Examples:
Input: N = 20
Output: 4
Explanation: 20! = 2432902008176640000 and it has 4 trailing zeros.Input: N = 6
Output: 1
Explanation: 6! = 720 and it has 1 trailing zero.
Approach: To solve the problem, follow the below idea:
If we observe carefully, the number of trailing zeros in N! is same as calculating the number of times the number N! is divisible by 10. We can find this by finding the number of pairs of {2, 5} in the prime factorization of N! as 2 * 5 = 10. Since the number of 2s will always be greater than the number of 5s in prime factorization of N!, therefore we can only calculate the number of 5s to calculate the total number of trailing zeros.
Also, the number of 5s in the prime factorization can be different for different numbers. Every multiple of 5 will have at least one 5 in the prime factorization. Similarly, every multiple of 25 will have at least two 5s and every multiple of 125 will have at least three 5s in the prime factorization as so on. So, we can first count the number of 5s for every multiple of 5 then for every multiple of 25, then 125 and so on to calculate the final answer.
Step-by-step algorithm:
Below is the implementation of the algorithm:
4
Time Complexity: O(log5N)
Auxiliary Space: O(1)