Multiply all the nonzero residues mod a prime. Mod 5: $1 \cdot 2 \cdot 3 \cdot 4 = 24 \equiv -1$. Mod 7: $6! = 720 \equiv -1$. It is always $-1$, and the reason is a pretty pairing argument with modular inverses.
Wilson's theorem. An integer $p > 1$ is prime exactly when $$(p - 1)! \equiv -1 \pmod{p}.$$
Why it works
Composites. If $n = ab$ with $1 < a < b < n$, both $a$ and $b$ appear in $(n - 1)!$, so $n \mid (n - 1)!$. If $n = a^{2}$ with $a > 2$, then $a$ and $2a$ both appear, so again $n \mid (n - 1)!$. Either way $(n - 1)! \equiv 0$, not $-1$. The lone exception $n = 4$ gives $3! = 6 \equiv 2$, still not $-1$.
Worked example: Checking the theorem
- Pair each number with its inverse mod 13: $2 \cdot 7 = 14$, $3 \cdot 9 = 27$, $4 \cdot 10 = 40$, $5 \cdot 8 = 40$, $6 \cdot 11 = 66$ are all $\equiv 1$.
- $12! \equiv 1 \cdot 12 \cdot 1^{5} = 12 \equiv -1 \pmod{13}$.
Answer: $12$, that is, $-1$.
Worked example: One factor short
- Wilson: $16! \equiv -1 \pmod{17}$. And $16! = 15! \cdot 16$ with $16 \equiv -1$.
- So $15! \cdot (-1) \equiv -1$, which gives $15! \equiv 1 \pmod{17}$.
Answer: $1$.
Worked example: Two factors short
- $22! = 20! \cdot 21 \cdot 22 \equiv 20! \cdot (-2)(-1) = 2 \cdot 20! \pmod{23}$, and $22! \equiv -1$.
- So $2 \cdot 20! \equiv -1$. The inverse of 2 mod 23 is 12, so $20! \equiv -12 \equiv 11 \pmod{23}$.
Answer: $11$.
| $n$ | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|
| $(n-1)! \bmod n$ | 1 | 2 | 2 | 4 | 0 | 6 | 0 | 0 | 0 | 10 |
Common mistake
Key idea