Last Updated: March 28, 2026
We need to count how many trailing zeroes appear at the end of n!. A trailing zero is a zero at the rightmost end of a number. For example, 120 has one trailing zero, and 1000 has three.
The naive instinct might be to compute n! and then count the zeroes at the end. But factorials grow astronomically fast. 20! is already over 2 billion, and 100! has 158 digits. So computing the full factorial is impractical for large n. We need a mathematical shortcut.
The key observation is this: a trailing zero is produced by a factor of 10, and 10 = 2 x 5. So the number of trailing zeroes equals the number of times 10 divides into n!, which equals the number of (2, 5) pairs in the prime factorization of n!. Since there are always more factors of 2 than 5 in a factorial (every even number contributes a 2, but only every fifth number contributes a 5), the bottleneck is the number of factors of 5.
0 <= n <= 10^4 → With n up to 10,000, even an O(n) approach is fine. But the follow-up asks for O(log n), which means there is a much more elegant mathematical solution.n can be 0 → Edge case where 0! = 1, which has zero trailing zeroes.Since trailing zeroes come from factors of 10 = 2 x 5, and factors of 2 are always more abundant than factors of 5 in a factorial, the number of trailing zeroes equals the number of times 5 appears as a factor across all numbers from 1 to n.
The straightforward approach: iterate through every number from 1 to n, and for each number, count how many times 5 divides it. Sum those counts up.
For example, in 10!, the numbers 5 and 10 each contribute one factor of 5, so the total is 2. In 25!, the number 25 contributes two factors of 5 (since 25 = 5 x 5), while 5, 10, 15, and 20 each contribute one, giving us 6 total.
count = 0.i from 1 to n:i is divisible by 5, divide i by 5 and increment count.count.We are iterating through every single number from 1 to n, even though 80% of them are not divisible by 5 at all. Instead of checking each number individually, can we directly count how many factors of 5 exist across the entire range at once?
Here is the key mathematical insight. Instead of iterating through every number and counting its factors of 5, we can count all factors of 5 in n! at once using a simple formula.
Think about it this way:
floor(n/5). Each one contributes at least one factor of 5.floor(n/25). Each of these contributes an extra factor of 5.floor(n/125). Each contributes yet another extra factor.So the total number of trailing zeroes is: floor(n/5) + floor(n/25) + floor(n/125) + floor(n/625) + ...
This is sometimes called Legendre's formula for counting the power of a prime p in n!.
Every second number is even, so factors of 2 are always more abundant than factors of 5. The count of (2, 5) pairs is limited by the scarcer factor, which is always 5.
count = 0.n >= 5:count.count.