A clear explanation of counting trailing zeroes in n! by counting factors of 5 instead of computing the factorial directly.
Problem Restatement
We are given a non-negative integer:
nWe need to return the number of trailing zeroes in:
n!where:
n! = 1 * 2 * 3 * ... * nA trailing zero is a zero at the end of the decimal representation.
For example:
1200has:
2trailing zeroes.
The problem asks us to compute the answer without explicitly calculating the factorial. The constraints allow values up to 10^4 on LeetCode, though the mathematical method works for much larger numbers. (leetcode.com)
Input and Output
| Item | Meaning |
|---|---|
| Input | Integer n |
| Output | Number of trailing zeroes in n! |
| Trailing zero | A factor of 10 at the end |
| Important restriction | Do not compute the factorial directly |
Example function shape:
def trailingZeroes(n: int) -> int:
...Examples
Example 1:
n = 3Compute:
3! = 6No trailing zeroes.
Return:
0Example 2:
n = 5Compute:
5! = 120There is one trailing zero.
Return:
1Example 3:
n = 10Compute:
10! = 3628800There are two trailing zeroes.
Return:
2First Thought: Compute the Factorial
One possible idea is:
factorial = 1
for i in range(1, n + 1):
factorial *= iThen repeatedly divide by 10.
This works for small numbers, but factorials grow extremely quickly.
For example:
100!already has a huge number of digits.
The problem expects a mathematical solution.
Key Insight
A trailing zero comes from a factor of:
10And:
10 = 2 * 5So the number of trailing zeroes equals the number of pairs:
(2, 5)inside the prime factorization of n!.
In factorials, factors of 2 are much more common than factors of 5.
So the limiting factor is the number of 5s.
Therefore:
The number of trailing zeroes equals the total number of factors of 5 inside n!.
Counting Factors of 5
Every multiple of 5 contributes at least one factor of 5.
Examples:
| Number | Factors of 5 contributed |
|---|---|
5 | 1 |
10 | 1 |
15 | 1 |
20 | 1 |
25 | 2 |
125 | 3 |
Notice:
25 = 5 * 5contributes two factors of 5.
And:
125 = 5 * 5 * 5contributes three.
So we must count all powers of 5.
The formula becomes:
n // 5
+ n // 25
+ n // 125
+ ...until the power exceeds n.
Why the Formula Works
Suppose:
n = 25Multiples of 5:
5, 10, 15, 20, 25That gives:
25 // 5 = 5factors of 5.
But 25 contributes an extra factor:
25 = 5 * 5So add:
25 // 25 = 1Total:
5 + 1 = 6Indeed:
25!has exactly 6 trailing zeroes.
Algorithm
Initialize:
answer = 0While n > 0:
- Divide
nby5. - Add the quotient to the answer.
- Continue with the smaller quotient.
Return the answer.
Walkthrough
Use:
n = 100First division:
100 // 5 = 20Add:
answer = 20Second division:
20 // 5 = 4Add:
answer = 24Third division:
4 // 5 = 0Stop.
Return:
24So: