Fermat's Two Squares Theorem

Fermat's Two Squares Theorem states that that a prime number $p$ can be represented as a sum of two nonzero squares if and only if $p = 2$ or $p \equiv 1 \pmod{4}$; and that this representation is unique.

Fermat first listed this theorem in 1640, but listed it without proof, as was usual for him. Euler gave the first written proof in 1747, by infinite descent.

The theorem is a starting point in the investigation of binary quadratic forms. Historically, two of the main questions have been:

  • What numbers does a form $F(x,y) = ax^2 + bxy + y^2$ represent?
  • In how many ways can an integer $n$ be represented by a form $F$?

The theorem, with some study of the Gaussian integers $\mathbb{Z}[i]$, resolves these questions for the form $x^2 + y^2$.

This theorem is also a special case of another general question in commutative algebra: What is the behavior of prime ideals under ring homomorphisms? This theorem resolves this question for the canonical injection $\mathbb{Z} \mapsto \mathbb{Z}[i]$, as follows:

  • The ideal $(2)$ becomes $(1+i)^2$;
  • For $p \equiv 1 \pmod{4}$, the ideal $(p)$ becomes $(a+bi)(a-bi)$, for some $a,b$; these ideals are then prime.
  • For $p \equiv 3 \pmod{4}$, the ideal $(p)$ remains prime.


Since 0 and 1 are the only quadratic residues mod 4, it follows that if $p$ is a prime number represented as the sum of two squares, then $p$ is even or $p\equiv 1 \pmod{4}$. The converse is more interesting.

We use the fact that the set of Gaussian integers $\mathbb{Z}[i]$ has a Euclidean algorithm. Hence it has unique prime factorization, and is a principal ideal domain (i.e., every ideal is a principal ideal). This is relevant because an integer can be represented (nontrivially) as a sum of two squares if and only if it has a (nontrivial) factorization in $\mathbb{Z}[i]$: \[p = a^2 + b^2 \iff p = (a+bi)(a-bi) .\]

Now, suppose that $p$ is a prime congruent to 1 mod 4 that cannot be represented as a sum of two squares. Then $p$ is a Gaussian prime, so $(p)\mathbb{Z}[i]$ is a prime ideal, and hence a maximal ideal. In other words, $\mathbb{Z}[i]/(p)$ is a field. But there is an element $k$ of $\mathbb{F}_p$ for which $k^2 = -1 \pmod{5}$. Then $k$, $-k$, $i$, and $-i$ are four distinct roots of the second-degree polynomial \[x^2 + 1\] in the commutative field $\mathbb{Z}[i]/(p)$. This is a contradiction.

Finally, we prove that the representation of a prime as a sum of two squares is unique. To this end, we note that if $p$ is a prime for which \[p = a^2 + b^2 = (a+bi)(a-bi),\] then $(a+bi)$ and $(a-bi)$ both have a prime norm; hence they are both Gaussian primes. Hence any such representation is unique up to multiplication by units. Since the only units in $\mathbb{Z}[i]$ are $\pm 1$ and $\pm i$, the representation is unique up to order and the sign of $a$ and $b$. $\blacksquare$

See also