Quant Memo
Foundational

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 10=2×510 = 2 \times 5. In n!n! (the product of every integer from 1 to nn), factors of 2 are far more plentiful than factors of 5 — roughly half the numbers up to nn are even, while only every fifth number contributes a factor of 5. So the number of trailing zeros in n!n! 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 n!n! is given by repeatedly dividing by increasing powers of 5 and summing the (rounded-down) results: n/5+n/25+n/125+\left\lfloor n/5 \right\rfloor + \left\lfloor n/25 \right\rfloor + \left\lfloor n/125 \right\rfloor + \dots, stopping once the power of 5 exceeds nn. The extra terms account for numbers like 25 or 125 that contribute more than one factor of 5 each.

For n=100n = 100: 100/5=20\lfloor 100/5 \rfloor = 20, 100/25=4\lfloor 100/25 \rfloor = 4, 100/125=0\lfloor 100/125 \rfloor = 0. Summing gives 20+4=2420 + 4 = 24, so 100!100! 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 n/5k\lfloor n/5^k \rfloor over increasing kk.

Related concepts

Practice in interviews

Further reading

  • Engel, Problem-Solving Strategies, ch. 1
ShareTwitterLinkedIn