How Tonelli-Shanks takes a square root mod p

Short answer: Tonelli-Shanks computes a square root of a modulo an odd prime p, given that a is a quadratic residue. Write p−1 = q·2^s with q odd. Find a quadratic nonresidue z, set an initial guess from a^{(q+1)/2}, and then walk a 2-power tower that corrects the guess by multiplying powers of z. The loop runs in O(s²) modular multiplications after the exponentiations, and s is small for most primes. If the Legendre symbol is −1, no square root exists.


What the problem actually asks

Half of the nonzero residues modulo an odd prime are squares, and each of those has two roots, r and p−r. For p ≡ 3 (mod 4) the root is a single exponentiation, a^{(p+1)/4}. For p ≡ 1 (mod 4) that exponent is not an integer. Tonelli-Shanks is the general algorithm. It uses a nonresidue as a generator of the hardest 2-power part of the multiplicative group.

The Legendre symbol (a/p) = a^{(p−1)/2} mod p is 1 when a is a nonzero residue, −1 when it is not, and 0 when p divides a. The algorithm should not be started when the symbol is −1.


What the algorithm guarantees

When a root exists, the algorithm returns one, and the other is its negation modulo p. The dominant cost is a few modular exponentiations of size log p, plus an O(s²) correction whose s is the valuation of p−1. Extra memory is a handful of residues. A nonresidue z can be found by testing random candidates. The probability a random unit is a nonresidue is one half, so the search is short. Deterministic search from 2 upward also works and is fast in practice.

The algorithm is for a prime modulus. A composite modulus makes the Legendre test and the group structure wrong. Square roots modulo a composite are a different problem and, for an RSA modulus, are equivalent in difficulty to factoring.


The working steps

  1. If a ≡ 0, return 0. Compute the Legendre symbol. If it is −1, report that no root exists. If p ≡ 3 (mod 4), return a^{(p+1)/4} mod p.
  2. Write p−1 = q·2^s with q odd. Find z whose Legendre symbol is −1. Set c = z^q mod p, r = a^{(q+1)/2} mod p, t = a^q mod p, and m = s.
  3. While t is not 1, find the smallest i in 1..m−1 such that t^{2^i} ≡ 1. Such an i exists because a is a residue and t has order dividing 2^{m−1}.
  4. Set b = c^{2^{m−i−1}} mod p. Replace r by r·b, t by t·b², c by b², and m by i.
  5. When t is 1, r is a square root. The other root is p−r.

The special case p ≡ 3 (mod 4) does not need the loop. The general loop needs a prime. Composite moduli are not handled by swapping in Euler’s criterion. Two roots are always returned as a pair of signs. A protocol that needs a canonical root should state which of r and p−r it keeps.


Approaches that look simpler and fail

Approach Why it fails when the modulus is treated as prime without a test
Run the exponent (p+1)/4 when p ≡ 1 (mod 4) The exponent is not an integer solution of the same identity. The result is not a square root in general. Use the full loop, or the special case only for p ≡ 3 (mod 4).
Skip the Legendre test A nonresidue makes the search for i fail or return a number whose square is not a. Test first.
Use the algorithm modulo a composite RSA number to avoid factoring Computing square roots modulo n = p·q is as hard as factoring n. Tonelli-Shanks does not provide a shortcut there.
Return only the smaller root when the caller needed both signs checked Both r and p−r square to a. A later equation may accept only one of them.

The exponentiation inside the algorithm is binary exponentiation. The residue test is the Legendre symbol, itself an exponentiation. Tonelli-Shanks is the prime-modulus square root.


A working example

This Python fragment takes a square root modulo an odd prime. Here p = 13 ≡ 1 (mod 4), so the p ≡ 3 shortcut does not apply and the full correction runs. One square root of 10 is 7, and 7² ≡ 10 (mod 13). The other root is 13−7.

def legendre(a, p):
    return pow(a, (p - 1) // 2, p)

def tonelli(a, p):
    a %= p
    if a == 0 or legendre(a, p) != 1:
        return None
    if p % 4 == 3:
        return pow(a, (p + 1) // 4, p)
    q, s = p - 1, 0
    while q % 2 == 0:
        q //= 2
        s += 1
    z = 2
    while legendre(z, p) != p - 1:
        z += 1
    m, c, r, t = s, pow(z, q, p), pow(a, (q + 1) // 2, p), pow(a, q, p)
    while t != 1:
        i, temp = 1, pow(t, 2, p)
        while temp != 1:
            temp = pow(temp, 2, p)
            i += 1
        b = pow(c, 1 << (m - i - 1), p)
        m = i
        c = pow(b, 2, p)
        r = r * b % p
        t = t * c % p
    return r

root = tonelli(10, 13)
assert root is not None and pow(root, 2, 13) == 10
print(root)

Where it is used

Tonelli-Shanks computes a square root modulo a prime, which is the step that decompresses an elliptic-curve point whose encoding stores the x-coordinate and a sign bit. OpenSSL’s modular square root uses that family of algorithms. A square root in the integers is Newton’s method.


When you can drop this algorithm

Drop the general loop for primes congruent to 3 modulo 4. One exponentiation is enough. Keep Tonelli-Shanks for a general odd prime, and refuse a composite modulus.


Why this stays published

We publish this so a search for Tonelli-Shanks returns the p ≡ 3 shortcut and the correction loop that handles every other odd prime. Tonelli-Shanks returns a square root modulo an odd prime by correcting an initial power with a quadratic nonresidue, after the Legendre symbol confirms that a root exists.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *