AlgoViz

Video lesson · Chapter 1 of 6

Order the costume changes

0:00 / 5:24

Factorials and trailing zeroes

1:27Reel

Read caption

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

Understand it

Start here

What a factorial is

The factorial of a non-negative integer nn, written n!n!, is the product of every whole number from 1 up to nn. So 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 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=1nk=1×2×⋯×n,0!=1n! = \prod_{k=1}^{n} k = 1 \times 2 \times \dots \times n, \qquad 0! = 1
The ∏\prod sign means multiply, the way ∑\sum means add. With no factors at all (the case n=0n = 0) the product is 1, the same way an empty sum is 0.
  • A product

    n!n! multiplies 11 to nn: 4!=244! = 24, 6!=7206! = 720, 10!=3,628,80010! = 3{,}628{,}800.

  • A count

    n!n! is the number of orderings of nn distinct things: 3 books, 6 orders.

  • A warning

    n!n! is the cost of trying every ordering. Past n≈12n \approx 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=63 \times 2 \times 1 = 6 orders: ABC, ACB, BAC, BCA, CAB, CBA.

Choices shrink by one per slot

The multiplication principle: independent choices multiply.

Permutations and combinations

P(n,r)=n!(n−r)!(nr)=n!r! (n−r)!(52)=5!2! 3!=10P(n, r) = \frac{n!}{(n-r)!} \qquad \binom{n}{r} = \frac{n!}{r!\,(n-r)!} \qquad \binom{5}{2} = \frac{5!}{2!\,3!} = 10
P(n,r)P(n, r) counts ordered picks of rr from nn; (nr)\binom{n}{r} counts unordered ones, dividing out the r!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!=1n! = n \times (n-1)! \quad\Rightarrow\quad 1! = 1 \times 0! \quad\Rightarrow\quad 0! = 1
Each factorial is the previous one times nn. Walk the rule backwards from 1!=11! = 1 and 0!0! must be 1.

factorial(4) unwinding

Without a base case the recursion would never stop. With 0!=10! = 1 every value comes out right.

In code

Computing n! in Python

Python
import mathdef factorial_loop(n):    result = 1                    # 0! = 1    for i in range(2, n + 1):        result *= i    return resultdef factorial_rec(n):    return 1 if n <= 1 else 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
ApproachTimeExtra spaceNotes
LoopO(n)O(n) multiplicationsO(1)O(1)The default. Start at 1, loop to nn inclusive.
RecursionO(n)O(n)O(n)O(n) call stackElegant; hits Python's recursion limit near 1,000.
math.factorialFastest in practiceO(1)O(1)Built in, exact for any size.
Mod 109+710^9 + 7O(n)O(n)O(1)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

nnn!n!Fits in
5120a byte
103,628,800int32
12479,001,600int32 (the last one)
136,227,020,800overflows int32
202.4×10182.4 \times 10^{18}int64 (the last one)
215.1×10195.1 \times 10^{19}overflows int64
int32 tops out at 2,147,483,647 and int64 at about 9.2×10189.2 \times 10^{18}.

Faster than any exponential

n!=1⋅2⋅3⋅4⏟24⋅5⋯n⏟each factor>2  >  2nfor n≥4n! = \underbrace{1 \cdot 2 \cdot 3 \cdot 4}_{24} \cdot \underbrace{5 \cdots n}_{\text{each factor} > 2} \;>\; 2^n \quad \text{for } n \ge 4
4!=24>24=164! = 24 > 2^4 = 16, and every later step multiplies n!n! by nn but 2n2^n only by 2. The same argument beats cnc^n for any constant cc once n>2cn > 2c.
How fast it climbs
  1. 15! = 120arrange a hand of cards
  2. 210! ≈ 3.6 millionbrute force still fine
  3. 313! ≈ 6.2 billiontoo slow, overflows int32
  4. 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 (ne)nn! \approx \sqrt{2\pi n}\,\left(\frac{n}{e}\right)^{n}
Already 99.2% accurate at n=10n = 10 (3,598,696 against 3,628,800), and the relative error keeps shrinking, roughly like 112n\frac{1}{12n}.

Take the log

log⁡2n!=nlog⁡2n−nlog⁡2e+O(log⁡n)=Θ(nlog⁡n)\log_2 n! = n \log_2 n - n \log_2 e + O(\log n) = \Theta(n \log n)
The simple bounds (n/2)n/2≤n!≤nn(n/2)^{n/2} \le n! \le n^n give the same Θ(nlog⁡n)\Theta(n \log n) without any calculus.
nnDigits of n!n!log⁡2n!\log_2 n!
10721.8
100158524.8
1,0002,568about 8,530
Digits of n!n! = ⌊log⁡10n!⌋+1\lfloor \log_{10} n! \rfloor + 1, computed by summing log⁡10k\log_{10} k instead of building the number.

Trailing zeroes

Where the zeros come from

10!=3,628,80010! = 3{,}628{,}800 ends in two zeros. A trailing zero appears every time the number has a factor of 10, and 10=2×510 = 2 \times 5. So the number of trailing zeros is the number of (2,5)(2, 5) pairs you can form from the prime factors of n!n!.

Zeros are pairs

zeros(n!)=min⁡(e2(n!),  e5(n!))\text{zeros}(n!) = \min\big(e_2(n!),\; e_5(n!)\big)
ep(m)e_p(m) is how many times the prime pp divides mm. In 10!10!, e2=8e_2 = 8 and e5=2e_5 = 2, so min⁡(8,2)=2\min(8, 2) = 2 zeros.

From factors to zeros

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!)e_2(n!) \ge e_5(n!) always, and the zero count is simply the number of 5s.

nn2s in n!n!5s in n!n!Trailing zeros
10822
252266
50471212
100972424
1,000994249249
The 2s are roughly four times the 5s: about nn against about n/4n/4.

Why, in one line

e2(n!)≈n2+n4+⋯≈ne5(n!)≈n5+n25+⋯≈n4e_2(n!) \approx \frac{n}{2} + \frac{n}{4} + \dots \approx n \qquad e_5(n!) \approx \frac{n}{5} + \frac{n}{25} + \dots \approx \frac{n}{4}
Both are geometric series. The ratio 1/21/2 beats 1/51/5 term by term, so the 2s always win.

The formula

Counting the 5s: Z(n)

Trailing zeros of n!

Z(n)=∑i≥1⌊n5i⌋=⌊n5⌋+⌊n25⌋+⌊n125⌋+…Z(n) = \sum_{i \ge 1} \left\lfloor \frac{n}{5^i} \right\rfloor = \left\lfloor \frac{n}{5} \right\rfloor + \left\lfloor \frac{n}{25} \right\rfloor + \left\lfloor \frac{n}{125} \right\rfloor + \dots
⌊n/5⌋\lfloor n/5 \rfloor counts the multiples of 5 (one five each). ⌊n/25⌋\lfloor n/25 \rfloor counts the multiples of 25, which hold an extra five. ⌊n/125⌋\lfloor n/125 \rfloor adds the third five of 125, 250, and so on. Z(25)=5+1=6Z(25) = 5 + 1 = 6, Z(100)=20+4=24Z(100) = 20 + 4 = 24.

The counting loop

One pass per power of 5 up to nn: ⌊log⁡5n⌋\lfloor \log_5 n \rfloor passes, so O(log n) time and O(1) space.
Python
import mathdef trailing_zeroes(n):    count, power = 0, 5    while power <= n:        count += n // power        power *= 5    return countdef brute(n):    s = str(math.factorial(n))    return len(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 in range(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⌊npi⌋e2(10!)=5+2+1=8e_p(n!) = \sum_{i \ge 1} \left\lfloor \frac{n}{p^i} \right\rfloor \qquad e_2(10!) = 5 + 2 + 1 = 8
Z(n)Z(n) is just this formula with p=5p = 5. It works for every prime pp.
QuestionUse
Trailing zeros in base 10e5(n!)e_5(n!), since 2s are plentiful
Trailing zeros in base 12 = 22×32^2 \times 3min⁡(⌊e2/2⌋,  e3)\min(\lfloor e_2 / 2 \rfloor,\; e_3)
Is (nr)\binom{n}{r} divisible by pp?ep(n!)−ep(r!)−ep((n−r)!)>0e_p(n!) - e_p(r!) - e_p((n-r)!) > 0
Largest kk with pkp^k dividing n!n!ep(n!)e_p(n!) directly
In a base bb, factor bb into primes and take the scarcest prime power.

In interviews

Factorials in algorithms

  • All permutations

    Generating every ordering of nn items is O(n⋅n!)O(n \cdot n!): LeetCode 46.

  • k-th permutation

    Divide kk by (n−1)!(n-1)!, (n−2)!(n-2)!, ... to pick each digit without generating the rest: LeetCode 60.

  • nCr mod p

    Precompute factorials and inverse factorials mod 109+710^9 + 7, then each (nr)\binom{n}{r} is O(1)O(1).

  • Catalan and derangements

    Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n}; derangements D(n)=(n−1)(D(n−1)+D(n−2))D(n) = (n-1)(D(n-1) + D(n-2)).

Which factorial tool fits?

Never build n!n! when the question is about its factors, and never enumerate n!n! orders when nn 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+710^9 + 7 at every multiplication when asked.
  • Check nn before brute-forcing orderings: 10! is fine, 13! is not.

Don't

  • Return 0 for 0!0!; it is 1.
  • Build n!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=1nkn! = \prod_{k=1}^{n} k counts the orderings of nn distinct items, and 0!=10! = 1 as the empty product.
  • P(n,r)=n!(n−r)!P(n, r) = \frac{n!}{(n-r)!} and (nr)=n!r!(n−r)!\binom{n}{r} = \frac{n!}{r!(n-r)!} come straight from it.
  • n!n! beats 2n2^n from n=4n = 4; 13! overflows int32 and 21! overflows int64.
  • Stirling: n!≈2πn(n/e)nn! \approx \sqrt{2\pi n}(n/e)^n, so log⁡n!=Θ(nlog⁡n)\log n! = \Theta(n \log n), 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⌋+…Z(n) = \lfloor n/5 \rfloor + \lfloor n/25 \rfloor + \dots runs in O(log n): Z(25)=6Z(25) = 6, Z(100)=24Z(100) = 24.
  • Legendre's formula ∑⌊n/pi⌋\sum \lfloor n/p^i \rfloor counts any prime in n!n!.

Sources