Wilson's Theorem

Theorem
A positive integer $$p$$ is a prime iff $$\left({p-1}\right)! \equiv -1 \pmod {p}$$.

Proof
If $$p = 2$$ the result is obvious.

Therefore we assume that $$p$$ is an odd prime.

If part
Consider $$n \in \Z, 1 \le n < p$$.

From Law of Inverses (Modulo Arithmetic), we have:
 * $$\exists n' \in \Z, 1 \le n' < p: n n' \equiv 1 \pmod p$$

as $$p$$ prime and therefore $$n \perp p$$.

By Congruence by Factors of Modulo, for each $$n$$ there is exactly one such $$n'$$, and $$\left({n'}\right)' = n$$.

So, provided $$n \ne n'$$, we can pair any given $$n$$ from $$1$$ to $$p$$ with another $$n'$$ from $$1$$ to $$p$$.

We are then left with the numbers such that $$n = n'$$.

Then we have $$n^2 \equiv 1 \pmod p$$.

Consider $$n^2 - 1 = \left({n+1}\right) \left({n-1}\right)$$ from Difference of Two Squares.

So either $$n+1$$ divides $$p$$ or $$n-1$$ does.

(They can't both do, as they have a difference of $$2$$, and $$p$$ is an odd prime.

From Congruence Modulo Negative Number‎, we have that $$p-1 \equiv -1 \pmod p$$.

Hence $$n=1$$ or $$n = p-1$$.

So, we have that $$\left({p-1}\right)!$$ consists of numbers multiplied together as follows:
 * in pairs whose product is congruent to $$1 \pmod p$$
 * the numbers $$1$$ and $$p-1$$.

The product of all these numbers is therefore congruent to $$1 \times 1 \times \cdots \times 1 \times p-1 \pmod p$$ by modulo multiplication.

From Congruence Modulo Negative Number we therefore have that $$\left({p-1}\right)! \equiv -1 \pmod {p}$$.

Only if part
Now consider $$p$$ is a composite, and $$q$$ is a prime such that $$q \backslash p$$.

Then both $$p$$ and $$\left({p-1}\right)!$$ are divisible by $$q$$.

If the congruence $$\left({p-1}\right)! \equiv -1 \pmod{p}$$ was satisfied, we would have $$\left({p-1}\right)! \equiv -1 \pmod {q}$$.

This would means $$0 \equiv -1 \pmod {q}$$ which is false.

Hence for $$p$$ composite, the congruence $$\left({p-1}\right)! \equiv -1 \pmod {p}$$ cannot hold.

Historical Note
This proof was attributed to John Wilson by Edward Waring in his 1770 edition of Meditationes Algebraicae.

It was first stated by Ibn al-Haytham ("Alhazen").

It appears also to have been known to Gottfried Leibniz before 1663.

It was in fact finally proved by Lagrange in 1793.