Inputs
Any integer.
Odd prime greater than 2.
The modulus is checked with the site's primality classifier: below 3.3 × 10²⁴ the answer is exact; above it p is only a probable prime, the returned roots are still verified, but completeness is stated assuming p is prime. Composite moduli are not handled here. Computation runs locally in your browser.
Result
—
Solution steps
Tonelli-Shanks iterations
| # | M | t | least i | b | new x | new t |
|---|
Method
A square root of a modulo p is a residue x with x² ≡ a (mod p). The calculator first reduces a modulo p.
Existence and count. The Legendre symbol decides existence: (a/p) = −1 means there is no root, a ≡ 0 gives the single root x\equiv 0, and (a/p) = 1 gives exactly two roots. Indeed, if x² ≡ y² (mod p) then p | (x − y)(x + y), and since p is prime, x ≡ ±y (mod p). So a nonzero residue has exactly the roots x and p-x.
Case p ≡ 3 (mod 4). Then
by Euler's criterion for a quadratic residue a.
Case p ≡ 5 (mod 8). Let v ≡ a^((p+3)/8) (mod p). If v² ≡ a then x=v; otherwise x ≡ v·i (mod p) with i ≡ 2^((p−1)/4), a square root of -1.
General case: Tonelli-Shanks. Write p − 1 = Q·2^S with Q odd (only factors of 2 are removed; nothing is factored). Find the smallest quadratic nonresidue z and set
Then x² ≡ a·t (mod p) holds from the start. Because a is a residue, t has order a power of 2. While t\ne 1: find the least i, 0<i<M, with t^(2^i) ≡ 1; put b = c^(2^(M−i−1)); then replace x by xb, c by b^{2}, t by tb^{2}, and M by i. The invariant x² ≡ a·t is preserved and the 2-power order of t strictly shrinks, so t reaches 1. Then x² ≡ a (mod p).
Verification. Every returned root r is checked directly: r² mod p = a mod p. For a probable-prime p each returned root is a verified fact, but "these are all the roots" and "there are no roots" hold only if p is actually prime.
Related: Legendre Symbol · Jacobi Symbol · Modular Exponentiation · Primality Test