Problem. How many zeros does end with?
The answer
, and always contains more factors of 2 than of 5 (every second number is even, only every fifth is a multiple of 5). So the count of trailing zeros is the exponent of 5:
long long trailingZeroes(long long n) {
long long c = 0;
for (long long p = 5; p <= n; p *= 5) c += n / p;
return c;
}. Note p *= 5 can overflow if written as n / p with p beyond n — the loop condition guards it.
Each term counts a different factor of 5: counts multiples of 5, counts the extra 5 contributed by multiples of 25, and so on.
Legendre’s formula
The general statement — the exponent of a prime in :
where is the digit sum of in base . The second form is a nice closed expression and shows immediately that .
long long legendre(long long n, long long p) {
long long e = 0;
for (long long q = p; q <= n; q *= p) e += n / q;
return e;
}Trailing zeros in other bases
Factor the base ; the answer is
long long trailingZeroesBase(long long n, long long b) {
long long best = LLONG_MAX;
for (long long q = 2; q * q <= b; q++) {
if (b % q) continue;
int a = 0;
while (b % q == 0) { b /= q; a++; }
best = min(best, legendre(n, q) / a);
}
if (b > 1) best = min(best, legendre(n, b));
return best;
}For base 12 : — and here the 2s are the binding constraint, unlike base 10.
The related results
| Question | Answer |
|---|---|
| Trailing zeros of | |
| Exponent of in | Legendre’s formula |
| Exponent of in | |
| Is divisible by ? | Kummer: iff adding and in base produces a carry |
| Lucas | |
| Last non-zero digit of | a periodic pattern; needs care with the removed 5s |
| Smallest with exactly trailing zeros | binary search — note some are unattainable |
Kummer’s theorem
The exponent of in equals the number of carries when adding and in base . A surprising and genuinely useful reformulation — it makes “is this binomial coefficient odd?” a one-line bit test:
The number of odd entries in row of Pascal’s triangle is therefore — the Sierpiński-triangle pattern.
Smallest with trailing zeros
is non-decreasing but skips values (it jumps by 2 at , by 3 at ), so not every is achievable. Binary search and verify equality:
long long smallestWithZeros(long long z) {
long long lo = 0, hi = 5 * (z + 1);
while (lo < hi) { long long mid = (lo + hi) / 2; if (trailingZeroes(mid) >= z) hi = mid; else lo = mid + 1; }
return trailingZeroes(lo) == z ? lo : -1; // unattainable
}Why it is worth knowing
It is the smallest problem that teaches “count the prime factorisation, not the number”. Computing and counting its zeros is impossible for ; counting the factors of 5 is four lines. That reframing — work with the exponents of primes rather than the value — is the standard approach to every divisibility question about factorials and binomials.
See also: Factorial Modulo p · Lucas Theorem · Wilson’s Theorem