Counting Trailing Zeros in a Factorial
A classic interview puzzle: how many zeros sit at the end of n! — solved by counting factors of 5, not factors of 10.
Prerequisites: Divisibility Tests and Digit Sums
A trailing zero at the end of a number comes from a factor of 10, and . In (the product of every integer from 1 to ), factors of 2 are far more plentiful than factors of 5 — roughly half the numbers up to are even, while only every fifth number contributes a factor of 5. So the number of trailing zeros in is limited entirely by how many times 5 divides into the product, not by how many times 2 does; there will always be more than enough 2s to pair with every 5.
The count of factors of 5 in is given by repeatedly dividing by increasing powers of 5 and summing the (rounded-down) results: , stopping once the power of 5 exceeds . The extra terms account for numbers like 25 or 125 that contribute more than one factor of 5 each.
For : , , . Summing gives , so ends in exactly 24 zeros.
Trailing zeros come from pairs of 2 and 5, and since 2s are abundant, the answer is always just the count of 5s: sum over increasing .
Related concepts
Practice in interviews
Further reading
- Engel, Problem-Solving Strategies, ch. 1