Sub topic 15
Powers of a Prime in \(n!\) and Trailing Zeros
Prerequisites and the core idea
Assume you can work with prime factorization, integer division, floor values, and powers. For a positive integer \(n\),
\[ n! = 1 \times 2 \times 3 \times \cdots \times n. \]
The power of a prime \(p\) in \(n!\) is the exponent of \(p\) in the prime factorization of \(n!\). It is written \(v_p(n!)\).
For example, \(v_2(10!)\) means the number of factors of 2 contained in \(10!\), after completely factorizing every number from 1 to 10.
Legendre’s formula
Counting only multiples of \(p\) is not enough because multiples of \(p^2,p^3,\ldots\) contain extra copies of \(p\). Legendre’s formula includes all of them:
\[ v_p(n!)=\left\lfloor\frac np\right\rfloor+ \left\lfloor\frac {n}{p^2}\right\rfloor+ \left\lfloor\frac {n}{p^3}\right\rfloor+\cdots \]
Stop when \(p^k>n\).
For \(v_5(100!)\):
\[ \left\lfloor\frac{100}{5}\right\rfloor+ \left\lfloor\frac{100}{25}\right\rfloor+ \left\lfloor\frac{100}{125}\right\rfloor =20+4+0=24. \]
Therefore, \(100!\) contains 24 factors of 5.
Why trailing zeros use the smaller exponent
A trailing zero is produced by a factor of 10:
\[ 10=2\times5. \]
Thus, the number of trailing zeros in \(n!\) is
\[ \min\big(v2(n!),v5(n!)\big). \]
For ordinary factorials, factors of 2 are much more common than factors of 5. Therefore,
\[ \text{trailing zeros of }n!=v_5(n!). \]
For \(100!\), the answer is 24, not 20. The four multiples of 25 contribute an additional factor of 5.
| Quantity | Calculation for \(100!\) | Value |
|---|---|---|
| \(v_5(100!)\) | \(20+4\) | 24 |
| \(v_2(100!)\) | \(50+25+12+6+3+1\) | 97 |
| Trailing zeros | \(\min(97,24)\) | 24 |
Common errors and CAT shortcuts
- Do not use only \(\lfloor n/p\rfloor\). Include \(p^2,p^3,\ldots\).
- Do not count the number of multiples of 10 directly when the factorial is large.
- For \(n!\), count powers of 5 unless the question changes the factors being multiplied.
- If the expression is a product such as \(n!(n+1)!\), calculate prime powers in both factorials and add them.
- To find the largest \(k\) such that \(p^k\mid n!\), compute \(vp(n!)\), then use \(k=vp(n!)\).
def prime_power_in_factorial(n, p):
count = 0
while n:
n //= p
count += n
return count
def trailing_zeros(n):
return prime_power_in_factorial(n, 5)
print(prime_power_in_factorial(100, 5)) # 24
print(trailing_zeros(100)) # 24Exercise
Find the number of trailing zeros in 250!.
Show answer
Compute floor(250/5) + floor(250/25) + floor(250/125) = 50 + 10 + 2 = 62. Therefore, 250! has 62 trailing zeros.