Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Count trailing zeroes in factorial of a number
In this article, we will learn how to count the number of trailing zeros in the factorial of a given number without actually computing the factorial itself.
Problem statement − We are given an integer n, we need to count the number of trailing zeros in n! (factorial of n).
Understanding the Concept
Trailing zeros are produced by factors of 10, and 10 = 2 × 5. In any factorial, there are always more factors of 2 than factors of 5, so we only need to count the factors of 5.
Algorithm
Count factors of 5 by dividing n by 5, then by 25, then by 125, and so on. Numbers like 25, 125 contribute multiple factors of 5.
Example
# trailing zero
def find(n):
# Initialize count
count = 0
# update Count
i = 5
while (n // i >= 1):
count += n // i
i *= 5
return count
# Driver program
n = 79
print(f"Count of trailing 0s in {n}! is {find(n)}")
The output of the above code is −
Count of trailing 0s in 79! is 18
How It Works
For n = 79:
- 79 ÷ 5 = 15 (numbers divisible by 5)
- 79 ÷ 25 = 3 (numbers divisible by 25, contributing extra factors)
- 79 ÷ 125 = 0 (no numbers divisible by 125)
- Total: 15 + 3 = 18 trailing zeros
Alternative Implementation
def count_trailing_zeros(n):
count = 0
power_of_5 = 5
while power_of_5 <= n:
count += n // power_of_5
power_of_5 *= 5
return count
# Test with multiple values
test_values = [5, 10, 25, 100]
for num in test_values:
zeros = count_trailing_zeros(num)
print(f"{num}! has {zeros} trailing zeros")
5! has 1 trailing zeros 10! has 2 trailing zeros 25! has 6 trailing zeros 100! has 24 trailing zeros
Key Points
- Time Complexity: O(log n) as we divide by powers of 5
- Space Complexity: O(1) using constant extra space
- We don't need to calculate the actual factorial
- Focus on counting factors of 5, not factors of 2
Conclusion
Counting trailing zeros in factorial requires counting factors of 5 using division by powers of 5. This efficient approach avoids computing large factorials and runs in O(log n) time.
