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
First let $$p$$ be a prime.

Since modular inverse modulo $$p$$ is a bijection in which only 1 and $$p-1$$ are mapped to themselves, numbers $$2, \ldots, p-2$$ can be divided into pairs $$\left({a, b}\right)$$, such that $$a b \equiv 1$$.

The product of all these numbers is therefore $$1$$.

By definition, $$\left({p-1}\right)!$$ is the product of $$1$$,$$p-1$$ and the numbers listed above.

Because of that, $$\left({p-1}\right)!$$ is congruent to $$1 \cdot \left({p-1}\right) \cdot 1 \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.