Sub topic 3
Trailing zeros of n!
This chapter assumes you know prime factorisation, laws of exponents, division with remainders, and the meaning of n! (the product 1 × 2 × ... × n).
A trailing zero is a zero at the end of a number in base 10. Each one needs a factor of 10, which is 2 × 5. In any factorial, factors of 2 outnumber factors of 5, so the count of 5s sets the answer.
Trailing zeros of n!
The number of trailing zeros of n! is floor(n/5) + floor(n/25) + floor(n/125) + ... Multiples of 25 contribute a second factor of 5, multiples of 125 a third, and so on.
For 100!, this gives 20 + 4 = 24 trailing zeros.
def trailing_zeros_factorial(n):
count = 0
p = 5
while p <= n:
count += n // p
p *= 5
return count
print(trailing_zeros_factorial(100)) # 24Trailing zeros of products and powers
Write the number as 2^a × 5^b × (other primes). Its trailing zeros equal min(a, b). For products and powers, add the exponents of 2 and of 5 across all factors first, then take the smaller total. For example, 40^10 = 2^30 × 5^10 has 10 trailing zeros.
Trailing zeros in other bases
In base b, one trailing zero means one factor of b. Factor b into primes. For each prime p with exponent e in b, find the exponent v of p in n! using floor(n/p) + floor(n/p^2) + ... Then take floor(v/e). The answer is the minimum of these values.
| Base | Prime factors | Exponent of 2 in 100! | Trailing zeros of 100! |
|---|---|---|---|
| 10 | 2 × 5 | 97 | 24 |
| 8 | 2^3 | 97 | 32 |
| 12 | 2^2 × 3 | 97 | 48 |
> Base 12 is limited by the factor 3, not 2. The exponent of 3 in 100! is 48, which is smaller than 97 // 2 = 48 only by tie, so both primes give 48.
Mixed CAT problems: picking a method and checking the answer
To check a answer under time pressure, recount using the other prime. For 25! × 8^3, the exponent of 2 is 22 + 9 = 31, and the exponent of 5 is 6. The answer is min(31, 6) = 6.
Exercise
How many trailing zeros does 200! have in base 10?
Show answer
floor(200/5) + floor(200/25) + floor(200/125) = 40 + 8 + 1 = 49.