Olympiad in Informatics

Quadratic Residue Study Notes

Problem Description

Given an expression \(x^2 \equiv n \pmod p\), find the value of \(x\). Here, if \(x\) has a solution, \(n\) is called a quadratic residue of \(p\).

The Legendre Symbol

First, we need to determine whether this equation has a root. Here we introduce the Legendre symbol to make the judgment. We define:

\[ \left( \frac{a}{p} \right) = \begin{cases} 1, a 为 p 的二次剩余 \\ -1, a 不是 p 的二次剩余 \\ 0, a \equiv 0 \pmod p \end{cases} \]

How do we tell by computation? Next we introduce Euler's criterion: for the Legendre symbol, we have

\[ \left( \frac{a}{p} \right) = a^{\frac{p-1}{2}} \pmod p \]

Proof: Consider the following cases separately

  • When \(\left( \frac{a}{p} \right) \equiv 1 \pmod p \), transform the expression into \(\sqrt{ a^{p-1} } \equiv 1 \pmod p\); by Fermat's little theorem, this is proved.
  • When \(\left( \frac{a}{p} \right) \equiv -1 \pmod p\), the quadratic residue does not exist. Simplify to \( a^{\frac{p-1}{2}} \equiv -1 \pmod p\). When no quadratic residue exists, there exist \(ij \equiv a \pmod p, i != j, i, j \in [1, p-1]\). It is known in number theory that there are \(\frac{p-1}{2}\) such pairs \((i,j)\) in total, so the Legendre expression can be further transformed into \( (p-1)! \equiv -1 \pmod p \); by Wilson's theorem, this is proved.

Cipolla's Algorithm

Having covered the black magic criterion formula above, let's bring in Cipolla's algorithm, which can compute quadratic residues. First, as with all quadratic equations, we need to check the roots first; just compute with the criterion above. After that, we randomly enumerate a \(c\) such that the Legendre symbol of \(c^2-n\) is \(-1\), and let \(i=\sqrt{c^2-n}\), forcibly taking the square root (somewhat like imaginary numbers). Then the following lemma gives the answer.

\[ x \equiv (n+i)^{\frac{p+1}{2}} \pmod p \]

Proof:

\[ \begin{aligned} x^2 & \equiv (n+i)^{p+1} \\ & \equiv (n+i)(n+i)^p \\ & \equiv (n+i)(n^p+i^p) \\ & \equiv (n+i)(n^p + (c^2-n)^{\frac{p-1}{2}} * i) \\ & \equiv (n+i)(n^p - i) \\ & \equiv (n+i)(n-i) \\ & \equiv n \end{aligned} \]

There are some shortcut steps in the proof, which I'll explain and prove here:

  • \((a+b)^n \equiv \sum^n_{i=0} C_n^i a^ib^{n-i} \equiv a^n+b^n \pmod p\); the middle terms are eliminated because of the binomial coefficient \(C_n^i\), which provides the factor \(n\).
  • By Fermat's little theorem, \(a^p \equiv a \pmod p\).