Apex › Cryptography

Square roots mod a prime (Tonelli–Shanks)

Solve x² ≡ n (mod p). Only half the residues are perfect squares (quadratic residues, two roots each); Euler’s criterion n^((p−1)/2) ≡ 1 says which. If p ≡ 3 (mod 4) the root is one exponentiation n^((p+1)/4); otherwise Tonelli–Shanks factors p−1 = Q·2^S, grabs a non-residue, and iterates to the root in O(log²p). The headline use: elliptic-curve point decompression — a compressed key stores only x and a sign bit, and recovering y = √(x³+ax+b) mod p needs a modular square root. Verified in node: x²≡n for every residue and null for every non-residue across 16 primes (916 roots), both branches, both roots x and p−x. Click a residue to test it and find its roots.

More in Cryptography