3! is 6, so it has no trailing zeros. 5! is 120, so it has one. The challenge was to count those zeros for any n in O(log n) time.
I started by calculating the whole factorial and peeling off its digits:
1 | import math |
Try imagining that with 999!. It’s a lot of work to build such a huge integer just to ask about its last few digits. And looking back, that loop counts every zero it sees, including ones in the middle.
A zero on the end means a factor of 10. That’s a pair of factors, 2 and 5. For example, 25 × 4 has two pairs, and 125 × 8 has three. Could I count the twos and fives in n! without multiplying everything out? I tried something a bit like a sieve:
1 | def func(n): |
The pow() approach was counting powers themselves. It missed the fact that a number like 10 contributes a five even though it isn’t a power of five.
The solution I looked up made it much simpler. There are more than enough even numbers to supply the twos. Count one five for every multiple of 5, an extra five for every multiple of 25, another for every multiple of 125, and so on. Here’s the version I originally wrote down:
1 | def func(n): |
There’s a slip in that last snippet: it stops as soon as the current number isn’t divisible by 5. For n = 6, that would return zero, even though 6! is 720. To carry the idea through, keep taking the integer quotient by 5 and adding it to the total until the quotient reaches zero.



