Uma counts the six trailing zeroes of 25 factorial without multiplying twenty-five numbers.
Count the fives and count their extra layers.
How it works
Step through the idea, or press Play.
Step 1 of 3
Multiply down to 1. n! = n × (n-1) × ... × 1, with 0! = 1, and it counts the orderings of n distinct items
Respect the growth. n! beats 2^n from n = 4, overflows int32 at 13! and int64 at 21!
Count factors, not digits. Trailing zeroes need a 2 and a 5 each; count the 5s with n/5 + n/25 + ... in O(log n)
Understand it
Start here
What a factorial is
The factorial of a non-negative integer n, written n!, is the product of every whole number from 1 up to n. So 5!=5×4×3×2×1=120. It answers one question that comes up everywhere in programming: in how many ways can I arrange $n$ distinct items?
The definition
n!=k=1∏nk=1×2×⋯×n,0!=1
The ∏ sign means multiply, the way ∑ means add. With no factors at all (the case n=0) the product is 1, the same way an empty sum is 0.
A product
n! multiplies 1 to n: 4!=24, 6!=720, 10!=3,628,800.
A count
n! is the number of orderings of n distinct things: 3 books, 6 orders.
A warning
n! is the cost of trying every ordering. Past n≈12 that is too slow.
Counting
Why n! counts arrangements
Put 3 books A, B, C on a shelf. The first slot can take any of 3 books. Once it is filled, 2 are left for the second slot, and the last slot gets the 1 that remains. Each choice multiplies the options, so there are 3×2×1=6 orders: ABC, ACB, BAC, BCA, CAB, CBA.
Choices shrink by one per slot
flowchart TD
S["n items to place"] --> A["Slot 1: n choices"]
A --> B["Slot 2: n - 1 choices"]
B --> C["Slot 3: n - 2 choices"]
C --> D["..."]
D --> E["Last slot: 1 choice"]
E --> T["Total: n x (n-1) x ... x 1 = n!"]
The multiplication principle: independent choices multiply.
Permutations and combinations
P(n,r)=(n−r)!n!(rn)=r!(n−r)!n!(25)=2!3!5!=10
P(n,r) counts ordered picks of r from n; (rn) counts unordered ones, dividing out the r! orders of each pick. These two formulas power most counting problems.
The base case
Why 0! = 1
The recursive definition
n!=n×(n−1)!⇒1!=1×0!⇒0!=1
Each factorial is the previous one times n. Walk the rule backwards from 1!=1 and 0! must be 1.
factorial(4) unwinding
flowchart TD
F4["factorial(4) = 4 x factorial(3)"] --> F3["factorial(3) = 3 x factorial(2)"]
F3 --> F2["factorial(2) = 2 x factorial(1)"]
F2 --> F1["factorial(1) = 1 x factorial(0)"]
F1 --> F0["factorial(0) = 1: base case"]
F0 --> R["Multiply back up: 1, 1, 2, 6, 24"]
Without a base case the recursion would never stop. With 0!=1 every value comes out right.
In code
Computing n! in Python
Python
importmathdeffactorial_loop(n): result = 1# 0! = 1for i inrange(2, n + 1): result *= ireturn resultdeffactorial_rec(n):return1if n <= 1else n * factorial_rec(n - 1)print(factorial_loop(5), factorial_rec(5), math.factorial(5)) # 120 120 120print(factorial_loop(0)) # 1print(len(str(math.factorial(100)))) # 158 digits
Three ways to get the same answer.Edit and run it in your browser
Approach
Time
Extra space
Notes
Loop
O(n) multiplications
O(1)
The default. Start at 1, loop to n inclusive.
Recursion
O(n)
O(n) call stack
Elegant; hits Python's recursion limit near 1,000.
math.factorial
Fastest in practice
O(1)
Built in, exact for any size.
Mod 109+7
O(n)
O(1)
result = result * i % MOD keeps numbers small.
Python ints never overflow, so all four are exact. In Java use BigInteger, in JavaScript BigInt.
Growth
Factorials explode
n
n!
Fits in
5
120
a byte
10
3,628,800
int32
12
479,001,600
int32 (the last one)
13
6,227,020,800
overflows int32
20
2.4×1018
int64 (the last one)
21
5.1×1019
overflows int64
int32 tops out at 2,147,483,647 and int64 at about 9.2×1018.
Faster than any exponential
n!=241⋅2⋅3⋅4⋅each factor>25⋯n>2nfor n≥4
4!=24>24=16, and every later step multiplies n! by n but 2n only by 2. The same argument beats cn for any constant c once n>2c.How fast it climbs
15! = 120arrange a hand of cards
210! ≈ 3.6 millionbrute force still fine
313! ≈ 6.2 billiontoo slow, overflows int32
420! ≈ 2.4 × 10^18longer than a lifetime
The growth ranking: $n! > 2^n > n^2 > n \log n > n$. See [O(n!) time](/learn/dsa/time-onfact) for what this means for algorithms.
Estimating
Stirling's approximation
Stirling's formula
n!≈2πn(en)n
Already 99.2% accurate at n=10 (3,598,696 against 3,628,800), and the relative error keeps shrinking, roughly like 12n1.
Take the log
log2n!=nlog2n−nlog2e+O(logn)=Θ(nlogn)
The simple bounds (n/2)n/2≤n!≤nn give the same Θ(nlogn) without any calculus.
n
Digits of n!
log2n!
10
7
21.8
100
158
524.8
1,000
2,568
about 8,530
Digits of n! = ⌊log10n!⌋+1, computed by summing log10k instead of building the number.
Trailing zeroes
Where the zeros come from
10!=3,628,800 ends in two zeros. A trailing zero appears every time the number has a factor of 10, and 10=2×5. So the number of trailing zeros is the number of (2,5) pairs you can form from the prime factors of n!.
Zeros are pairs
zeros(n!)=min(e2(n!),e5(n!))
ep(m) is how many times the prime p divides m. In 10!, e2=8 and e5=2, so min(8,2)=2 zeros.
From factors to zeros
flowchart LR
F["Prime factors of n!"] --> T["Count the 2s"]
F --> V["Count the 5s"]
T --> P["Pair each 5 with a 2"]
V --> P
P --> Z["Each pair makes one 10, one trailing zero"]
Leftover 2s cannot make a zero without a 5 to pair with.
The key insight
Why the 2s are never the bottleneck
Every second number is even and contributes a 2, every fourth contributes another, and so on. Only every fifth number contributes a 5. The 2s pile up much faster, so e2(n!)≥e5(n!) always, and the zero count is simply the number of 5s.
n
2s in n!
5s in n!
Trailing zeros
10
8
2
2
25
22
6
6
50
47
12
12
100
97
24
24
1,000
994
249
249
The 2s are roughly four times the 5s: about n against about n/4.
Why, in one line
e2(n!)≈2n+4n+⋯≈ne5(n!)≈5n+25n+⋯≈4n
Both are geometric series. The ratio 1/2 beats 1/5 term by term, so the 2s always win.
The formula
Counting the 5s: Z(n)
Trailing zeros of n!
Z(n)=i≥1∑⌊5in⌋=⌊5n⌋+⌊25n⌋+⌊125n⌋+…
⌊n/5⌋ counts the multiples of 5 (one five each). ⌊n/25⌋ counts the multiples of 25, which hold an extra five. ⌊n/125⌋ adds the third five of 125, 250, and so on. Z(25)=5+1=6, Z(100)=20+4=24.
The counting loop
flowchart TD
S["count = 0, power = 5"] --> Q{"power <= n?"}
Q -- yes --> A["count += n // power"]
A --> M["power *= 5"]
M --> Q
Q -- no --> R["Return count"]
One pass per power of 5 up to n: ⌊log5n⌋ passes, so O(log n) time and O(1) space.
Python
importmathdeftrailing_zeroes(n): count, power = 0, 5while power <= n: count += n // power power *= 5return countdefbrute(n): s = str(math.factorial(n))returnlen(s) - len(s.rstrip("0"))print(trailing_zeroes(25), trailing_zeroes(100), trailing_zeroes(1000)) # 6 24 249print(all(trailing_zeroes(n) == brute(n) for n inrange(300))) # True
LeetCode 172 in six lines, checked against brute force.Edit and run it in your browser
Going further
Legendre's formula: any prime
Legendre's formula
ep(n!)=i≥1∑⌊pin⌋e2(10!)=5+2+1=8
Z(n) is just this formula with p=5. It works for every prime p.
Question
Use
Trailing zeros in base 10
e5(n!), since 2s are plentiful
Trailing zeros in base 12 = 22×3
min(⌊e2/2⌋,e3)
Is (rn) divisible by p?
ep(n!)−ep(r!)−ep((n−r)!)>0
Largest k with pk dividing n!
ep(n!) directly
In a base b, factor b into primes and take the scarcest prime power.
In interviews
Factorials in algorithms
All permutations
Generating every ordering of n items is O(n⋅n!): LeetCode 46.
k-th permutation
Divide k by (n−1)!, (n−2)!, ... to pick each digit without generating the rest: LeetCode 60.
nCr mod p
Precompute factorials and inverse factorials mod 109+7, then each (rn) is O(1).
flowchart TD
Q1{"Asked for zeros or prime factors of n!?"} -- yes --> L["Legendre: sum of n // p^i, O(log n)"]
Q1 -- no --> Q2{"Counting arrangements or selections?"}
Q2 -- yes --> Q3{"Answer may be huge?"}
Q3 -- yes --> M["Factorials mod 1e9+7 with inverses"]
Q3 -- no --> C["n!, P(n, r) or nCr directly"]
Q2 -- no --> Q4{"Must try every ordering?"}
Q4 -- yes --> B["O(n!) brute force: only for n up to about 10"]
Q4 -- no --> O["Look for a DP or greedy instead"]
Never build n! when the question is about its factors, and never enumerate n! orders when n is large.
Do
Start the product at 1 and loop with range(2, n + 1).
Count factors of 5 for trailing zeros, including 25, 125, ...
Reduce mod 109+7 at every multiplication when asked.
Check n before brute-forcing orderings: 10! is fine, 13! is not.
Don't
Return 0 for 0!; it is 1.
Build n! and scan its digits to count zeros.
Use int in Java or C++ past 12!, or long past 20!.
Recurse thousands deep in Python for a plain factorial.
Recap
Key takeaways
Key points
n!=∏k=1nk counts the orderings of n distinct items, and 0!=1 as the empty product.
P(n,r)=(n−r)!n! and (rn)=r!(n−r)!n! come straight from it.
n! beats 2n from n=4; 13! overflows int32 and 21! overflows int64.
Stirling: n!≈2πn(n/e)n, so logn!=Θ(nlogn), the sorting lower bound.
Trailing zeros need a 2 and a 5 each. The 2s are never the bottleneck, so count the 5s.
Z(n)=⌊n/5⌋+⌊n/25⌋+… runs in O(log n): Z(25)=6, Z(100)=24.
Legendre's formula ∑⌊n/pi⌋ counts any prime in n!.