← LibrarySquare Roots Modulo a PrimeEngineering · MathematicsLesson 9/11← PrevNext →
GuidePublished 6 Aug 20264 min readBy Kevin JoginComputational Number TheoryFoundational AlgorithmsTonelli-ShanksModular Square Root
Skip to the main content

MathematicsFoundational Algorithms

Square Roots Modulo a Prime

Tonelli–Shanks in the general case, the fast congruence shortcuts, and Cornacchia's algorithm for representing primes by quadratic forms.

Executive summary

Extracting a square root when the modulus is prime

When p ≡ 3 (mod 4) a square root is a single modular exponentiation. The general case is harder because the 2-part of the group (ℤ/pℤ)* is non-trivial; Tonelli–Shanks resolves it by walking down that 2-part one level at a time, using a known non-residue as a lever. Cornacchia's algorithm then converts a modular square root of −d into an integer representation x2 + dy2 = p.

Learning objectives

  • Apply the congruence shortcuts where they exist.
  • Explain the 2-adic structure that Tonelli–Shanks exploits.
  • Analyse the algorithm's cost in terms of the 2-part of p−1.
  • Use Cornacchia's algorithm to represent a prime by a quadratic form.

Section 01Shortcuts by congruence class

Write p − 1 = 2eq with q odd. The difficulty is governed entirely by e.

Square-root strategies by the 2-part of p−1
CaseeMethodCost
p ≡ 3 (mod 4)1x = a(p+1)/4 mod pOne exponentiation
p ≡ 5 (mod 8)2One exponentiation plus a correction by a power of 2One exponentiation
p ≡ 1 (mod 8)≥ 3Tonelli–Shanks or CipollaO(e2) extra multiplications
Why 3 mod 4 works

If a is a residue then a(p−1)/2 = 1, so (a(p+1)/4)2 = a(p+1)/2 = a · a(p−1)/2 = a. The exponent (p+1)/4 is an integer precisely because p ≡ 3 (mod 4).

Section 02The Tonelli–Shanks algorithm

AlgorithmTonelli–Shanksin: prime p, residue a  →  out: x with x² ≡ a (mod p)
  1. Verify (a/p) = 1; otherwise no square root exists.
  2. Write p − 1 = 2eq with q odd.
  3. Find a quadratic non-residue n by random search; set z ← nq mod p. z generates the 2-Sylow subgroup.
  4. Set y ← z, r ← e, x ← a(q−1)/2, b ← a x2, x ← a x.
  5. While b ≠ 1: find the least m with b2^m = 1. m measures the remaining 2-power obstruction.
  6.    Set t ← y2^(r−m−1), y ← t2, r ← m.
  7.    Set x ← x t and b ← b y.
  8. Return x, with x2 ≡ a (mod p).
Invariant: a x−2 b = 1 and b has order dividing 2r, with r strictly decreasing. Each iteration removes at least one power of 2 from the obstruction, so at most e iterations occur.
Finding the non-residue

No deterministic method for finding a non-residue is known that is unconditionally fast, so random search is used: half of all residues qualify, so the expected number of trials is 2. This randomisation is the only non-deterministic element of the algorithm, and it does not affect correctness — only running time.

Section 03Cornacchia's algorithm

Given a prime p and d > 0 with −d a residue modulo p, Cornacchia's algorithm decides whether x2 + dy2 = p is solvable and produces the solution. It is a partial Euclidean algorithm with an early stop.

AlgorithmCornacchia's algorithmin: prime p, d > 0  →  out: (x, y) with x² + dy² = p, or none
  1. Compute a square root x0 of −d modulo p with p/2 < x0 < p.
  2. Run the Euclidean algorithm on (p, x0), stopping at the first remainder a < √p. The early stop is the essential step.
  3. Set t ← p − a2. If d does not divide t, report no solution.
  4. If t/d is not a perfect square, report no solution.
  5. Return (x, y) = (a, √(t/d)).
The special case d = 1 is the classical representation of a prime p ≡ 1 (mod 4) as a sum of two squares.
Where this is needed

Cornacchia's algorithm supplies the representations used to construct elliptic curves with prescribed complex multiplication — the foundation of the CM method for curve generation and of Atkin's primality test.

ReferenceFrequently asked questions

What happens if I run Tonelli-Shanks on a composite modulus?

It fails silently or loops, because the algorithm assumes the group structure of a field. Square roots modulo a composite are computed instead by finding roots modulo each prime power and combining by CRT — which requires the factorisation, and is why square roots modulo a composite are computationally equivalent to factoring.

Is Cipolla's algorithm better than Tonelli-Shanks?

Cipolla works in a quadratic extension and costs O(log p) extension-field multiplications regardless of the 2-part of p−1. It wins when p−1 is divisible by a very large power of 2; Tonelli–Shanks wins in the common case where that power is small.

How do I get the other square root?

The two roots are x and p−x, and there are exactly two for a non-zero residue modulo an odd prime. Implementations usually return the smaller, but this is convention, not mathematics — check the documentation before relying on it.

NavigateContinue in this stream

Curated next steps from this page. The site also surfaces algorithmically related reading below.

ProvenanceSources and further reading

This page is an original KEVOS explanatory article. It presents the underlying mathematics — definitions, algorithms, complexity results and selection criteria — in KEVOS editorial voice. No text is reproduced from any copyrighted source. Where numerical tables are relevant, KEVOS links to live authoritative databases rather than republishing static values.

Page ID
KV-MATH-0009
Taxonomy
ENG-MATH — Engineering / Mathematics
Collection
COL-CANT-001
Topic stream
CANT-FOUNDATIONS
Version
1.1.0 / content 2026.08
Last reviewed
2026-08-06

Continue learning

Legendre, Jacobi and Kronecker SymbolsGuide · MathematicsNEXT LESSON →Solving Polynomial Equations Modulo pGuide · MathematicsContinued Fraction ExpansionsGuide · MathematicsInteger Square Roots and Perfect Power DetectionGuide · Mathematics