Have you ever wondered how to calculate the number of trailing zeros in a factorial? In this post, I will explain the process of finding them and provide a Python program to compute the count.
What Are Trailing Zeros?
Trailing zeros are the sequence of zeros at the end of a number. For example, the number 1000 has 3 trailing zeros, and the number 300 has 2 trailing zeros. In the context of factorials, trailing zeros are created by multiplying 10s, and each 10 is the product of 2 and 5. For instance, 10!
(10 factorial), which equals 3,628,800, has 2 trailing zeros.
Why Count Powers of 5?
In the prime factorization of a factorial, there are always more 2s than 5s. This is because even numbers (which contribute factors of 2) are more frequent than multiples of 5. Therefore, the number of trailing zeros is determined by the number of 5s in the prime factorization of n!
.
The Formula
The number of trailing zeros in n!
is calculated by counting the number of times n can be divided by powers of 5:
This continues until the division results in a value less than 1.
Example:
\[ \text{Number of trailing zeros in 50!} = \left\lfloor \frac{50}{5} \right\rfloor + \left\lfloor \frac{50}{25} \right\rfloor = 12 \]Here is a simple Python program that computes the number of trailing zeros in n!
:
import argparse
def count_trailing_zeros(n):
"""
compute the number of trailing zero in n!
"""
count = 0
power_of_5 = 5
while power_of_5 <= n:
count += n // power_of_5 # Add the quotient to the count
power_of_5 *= 5 # Move to the next power of 5
return count
def main():
"""
python code to find number of trailing zeros in n!
"""
# set up argument parser
parser = argparse.ArgumentParser(description="Number of trailing zeros in n!")
parser.add_argument("-n", type=int, required=True, help="Enter a number")
args = parser.parse_args()
print(f"The number of trailing zeros in {args.n}! is: {count_trailing_zeros(args.n)}")
if __name__ == "__main__":
main()
To run this code, save it as fact_trail_zeros.py
(or any name you prefer) and execute it from the command line, providing a number as an argument, as shown below:
python fact_trail_zeros.py -n 100
The code will return the count of trailing zeros in the factorial of the given number (n!
). If you encounter any issues with the code, please let me know in the comments.