Why it holds

In , pair every element with its inverse. The pairs cancel to 1, except for the self-inverse elements — those with , i.e. . So the product of everything is .

For composite , the factors and both appear in , so and the product is . ( gives .) That makes Wilson’s theorem an exact primality characterisation — though a useless one computationally, since computing takes .

The useful consequences

Factorial complements

Concretely, , and more generally you can convert a factorial near into a small one — useful when a formula involves for small .

Wilson’s quotient and prime powers


holds only for Wilson primes: 5, 13, and 563. No others are known below .

Factorial modulo with a factor removed

Define as the product of integers not divisible by . Then Wilson gives

which is the engine of the generalised Lucas theorem — see Factorial Modulo p.

TheoremStatement
Wilson iff prime
Fermat for
Euler for
Lucas in base
Legendrethe exponent of in is
Kummerthat exponent in = number of carries adding and in base

Legendre’s formula — the practical one

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;
}

This is how you compute:

  • trailing zeros of (there are always more 2s than 5s);
  • the exact power of dividing ;
  • whether is divisible by — equivalently, by Kummer’s theorem, whether adding and in base produces a carry.

See Trailing Zeroes.

Where Wilson actually gets used

  • Computing when — the answer is 0 unless you mean the -free factorial, which Wilson evaluates.
  • Generalised Lucas for (Andrew Granville’s method).
  • Proof exercises — Wilson gives quick proofs that is a QR modulo iff : take and check .
  • Primality testing — theoretically exact, practically useless; use Miller-Rabin.

See also: Factorial Modulo p · Lucas Theorem · Combinatorics