FLINT3.7.0-dev
Algorithm

Square roots modulo a prime

Cost
O(log⁡n)O(\log n) modular multiplications if n≢1(mod8)n \not\equiv 1 \pmod 8. Otherwise, with n−1=q2sn - 1 = q 2^s and qq odd, O(log⁡n+s2)O(\log n + s^2) multiplications for Tonelli–Shanks, or O(log⁡n)O(\log n) multiplications and a few Jacobi symbols for Müller's method.

Given a prime nn and a∈Z/nZa \in \mathbb{Z}/n\mathbb{Z}, we want rr with r2=ar^2 = a. Half of the nonzero residues are squares. For aa a square, the two roots are rr and n−rn - r, and nmod_sqrt returns the one in [0,n/2][0, n/2]. The choice of method depends on n mod 8n \bmod 8 and on the 2-adic valuation ss of n−1n - 1. Standard references are [Coh1996] and [CraPom2005].

Overview#

nmod_sqrt(res, a, mod) proceeds as follows.

  1. If a≤1a \le 1, return aa. If nn is even, return failure.
  2. If n<128n < 128 (NMOD_SQRT_SMALL_CUTOFF), search t=1,2,…,⌊n/2⌋t = 1, 2, \ldots, \lfloor n/2 \rfloor with t2t^2 updated incrementally (_nmod_sqrt_small). This is exact for any odd nn.
  3. Otherwise choose the arithmetic: half-word lazy Montgomery arithmetic if n<2FLINT_BITS/2−2n < 2^{\mathtt{FLINT\_BITS}/2 - 2}, full-word lazy Montgomery arithmetic if n<2FLINT_BITS−2n < 2^{\mathtt{FLINT\_BITS} - 2}, and plain Montgomery arithmetic otherwise. All remaining steps work in Montgomery form, and the three versions are compiled separately so that each is fully inlined.
  4. Compute a candidate root rr:

    • n≡3(mod4)n \equiv 3 \pmod 4: Algorithm 1;
    • n≡5(mod8)n \equiv 5 \pmod 8: Algorithm 2;
    • n≡1(mod8)n \equiv 1 \pmod 8: Algorithm 5 if 6s≥b+1206s \ge b + 120, where bb is the bit length of nn, and if it finds a suitable parameter; otherwise Algorithm 3 for s<12s < 12 and Algorithm 4 for s≥12s \ge 12.
  5. Return rr if r2=ar^2 = a, and failure otherwise.

No Jacobi symbol of aa is computed in advance. For prime nn, every method below returns a correct root when aa is a square, so the final check is a complete test of whether aa is a square. For composite nn, the check guarantees that a returned root is genuine, but a failure proves nothing.

The branches in the inner loops are replaced by masks and selections, since their conditions depend on random data and would be mispredicted. For the same reason, exponentiation multiplies by 1 instead of skipping a multiplication when an exponent bit is 0.

The case n≡3(mod4)n \equiv 3 \pmod 4#

Algorithm 1

Input: prime n≡3(mod4)n \equiv 3 \pmod 4 and aa.

Output: a candidate root rr.

  1. Return r=a(n+1)/4r = a^{(n+1)/4}.

If aa is a square, Euler's criterion gives a(n−1)/2=1a^{(n-1)/2} = 1, so r2=a(n+1)/2=a⋅a(n−1)/2=ar^2 = a^{(n+1)/2} = a \cdot a^{(n-1)/2} = a.

The case n≡5(mod8)n \equiv 5 \pmod 8#

Here −1-1 is a square and 22 is not. Atkin's method [Atk1992] uses a square root of −1-1 built from 2a2a.

Algorithm 2: Atkin

Input: prime n≡5(mod8)n \equiv 5 \pmod 8 and a≠0a \ne 0.

Output: a candidate root rr.

  1. t←2at \gets 2a and b←t(n−5)/8b \gets t^{(n-5)/8}.
  2. i←tb2i \gets t b^2.
  3. Return r=ab(i−1)r = ab(i - 1).

Theorem 1. If aa is a nonzero square modulo the prime n≡5(mod8)n \equiv 5 \pmod 8, then Algorithm 2 returns a square root of aa.

Proof. We have i=t(n−1)/4i = t^{(n-1)/4}, so i2=(2a)(n−1)/2=−1i^2 = (2a)^{(n-1)/2} = -1, because 2 is a nonsquare and aa is a square. Hence (i−1)2=i2−2i+1=−2i(i - 1)^2 = i^2 - 2i + 1 = -2i and

r2=a2b2(−2i)=−ai⋅(2ab2)=−ai2=a.r^2 = a^2 b^2 (-2i) = -a i \cdot (2a b^2) = -a i^2 = a.

Tonelli–Shanks#

For n≡1(mod8)n \equiv 1 \pmod 8 write n−1=q2sn - 1 = q 2^s with qq odd, so s≥3s \ge 3. The method of Tonelli [Ton1891] and Shanks [Sha1973] works in the subgroup of order 2s2^s of (Z/nZ)×(\mathbb{Z}/n\mathbb{Z})^\times, which is cyclic.

Nonresidue. It needs some kk that is not a square. FLINT takes the least odd prime k≤61k \le 61 with Jacobi symbol (k∣n)=−1(k \mid n) = -1, and otherwise the least odd k≥67k \ge 67 with (k∣n)=−1(k \mid n) = -1. Only odd primes need to be tried among the small values, because the least nonresidue is prime and 2 is a square for n≡1(mod8)n \equiv 1 \pmod 8. By quadratic reciprocity (k∣n)=(n∣k)(k \mid n) = (n \mid k), and (n∣k)(n \mid k) is read from a bitmask indexed by n mod kn \bmod k, computed with two multiplications instead of a division: with m=nk−1 mod Bm = n k^{-1} \bmod B, the high word hh of mkmk satisfies mk=n+hBmk = n + hB, so n≡−hB(modk)n \equiv -hB \pmod k, and since BB is a square, (n∣k)=(−h∣k)(n \mid k) = (-h \mid k). The search gives up, which makes nmod_sqrt fail, if nn is found to be a perfect square or no nonresidue is found below 2202^{20}; neither happens for prime nn.

Setup. With u=a(q−1)/2u = a^{(q-1)/2} and c=k(q−1)/2c = k^{(q-1)/2}, both computed by one exponentiation loop that interleaves the two independent squaring chains, set

r=ua=a(q+1)/2,t=ur=aq,g=c2k=kq.r = ua = a^{(q+1)/2}, \qquad t = ur = a^q, \qquad g = c^2 k = k^q.

Then r2=atr^2 = a t, and gg has order exactly 2s2^s since g2s−1=k(n−1)/2=−1g^{2^{s-1}} = k^{(n-1)/2} = -1. If aa is a square, then t2s−1=a(n−1)/2=1t^{2^{s-1}} = a^{(n-1)/2} = 1. It remains to find xx with tgx=1t g^x = 1; then xx is even when aa is a square, and rgx/2r g^{x/2} is a root.

Algorithm 3: Tonelli–Shanks descent

Input: r,t,gr, t, g as above, with r2=atr^2 = at and gg of order 2s2^s.

Output: a root rr of aa, or failure.

  1. m←sm \gets s.
  2. While t≠1t \ne 1:

    1. Find the least ii with 0<i<m0 < i < m and t2i=1t^{2^i} = 1, by repeated squaring. If there is none, return failure.
    2. b←g2m−i−1b \gets g^{2^{m - i - 1}}, g←b2g \gets b^2, t←tgt \gets t g, r←rbr \gets r b, m←im \gets i.
  3. Return rr.

Theorem 2. If aa is a nonzero square modulo the prime nn, then Algorithm 3 terminates and returns a square root of aa. If aa is not a square, it returns failure.

Proof. The loop maintains r2=atr^2 = at, gg of order exactly 2m2^m, and t2m−1=1t^{2^{m-1}} = 1. This holds initially. In step 2.1, t≠1t \ne 1 and t2m−1=1t^{2^{m-1}} = 1, so ii exists and tt has order exactly 2i2^i. Then bb has order 2i+12^{i+1}, so b2b^2 has order 2i2^i. In a cyclic group, the elements of order exactly 2i2^i all satisfy x2i−1=−1x^{2^{i-1}} = -1, so (tb2)2i−1=1(t b^2)^{2^{i-1}} = 1. The updates give (rb)2=atb2=atnew(rb)^2 = at b^2 = a t_{\text{new}}, and the invariant holds with m=im = i. Since mm decreases strictly, the loop terminates, and on exit t=1t = 1 and r2=ar^2 = a. If aa is not a square, then t2s−1=−1t^{2^{s-1}} = -1, so no i<si < s exists in the first round.

Each round costs up to mm dependent squarings, so the total is O(s2)O(s^2) multiplications in one long dependency chain. This is cheap for small ss, which is the common case: asymptotically, half of the primes n≡1(mod8)n \equiv 1 \pmod 8 have s=3s = 3. FLINT uses it for s<12s < 12.

Bitwise variant#

For larger ss the latency of the dependent squarings dominates. The second form finds the bits x0,x1,…x_0, x_1, \ldots of xx from the bottom, as in Pohlig–Hellman (see Discrete logarithms modulo a prime (Pohlig–Hellman)), using products that do not depend on each other.

Algorithm 4: Tonelli–Shanks by bits

Input: r,t,gr, t, g as above.

Output: a root rr of aa, or failure.

  1. For 0≤i<s0 \le i < s: Di←t2iD_i \gets t^{2^i} and Gi←g2iG_i \gets g^{2^i}.
  2. If Ds−1≠1D_{s-1} \ne 1, return failure.
  3. For j=1,…,s−1j = 1, \ldots, s - 1: if Ds−1−j≠1D_{s-1-j} \ne 1, set Di←DiGi+jD_i \gets D_i G_{i+j} for 0≤i<s−1−j0 \le i < s - 1 - j, and r←rGj−1r \gets r G_{j-1}.
  4. Return rr.

Theorem 3. If aa is a nonzero square modulo the prime nn, then Algorithm 4 returns a square root of aa. If aa is not a square, it returns failure.

Proof. Let x∈[0,2s)x \in [0, 2^s) with tgx=1t g^x = 1, which exists because tt lies in the cyclic group generated by gg. Let XjX_j be the part of xx below bit jj. We claim that before iteration jj of step 3, Di=(tgXj)2iD_i = (t g^{X_j})^{2^i} for i≤s−1−ji \le s - 1 - j, and r=a(q+1)/2gXj/2r = a^{(q+1)/2} g^{X_j/2}.

Since tgXj=g−(x−Xj)t g^{X_j} = g^{-(x - X_j)} and 2j2^j divides x−Xjx - X_j, we get Ds−1−j=g−2s−1(x−Xj)/2j=(−1)xjD_{s-1-j} = g^{-2^{s-1} (x - X_j)/2^j} = (-1)^{x_j}, so the test in step 3 reads off bit xjx_j. Setting the bit multiplies tgXjt g^{X_j} by g2jg^{2^j}, hence each DiD_i by Gi+jG_{i+j}, and rr by g2j−1=Gj−1g^{2^{j-1}} = G_{j-1}. Only DiD_i with i<s−1−ji < s - 1 - j are used later. Step 2 is the case j=0j = 0: Ds−1=a(n−1)/2D_{s-1} = a^{(n-1)/2}, which is 1 if and only if aa is a square, and then x0=0x_0 = 0. At the end X=xX = x and r2=aq+1gx=a⋅tgx=ar^2 = a^{q+1} g^{x} = a \cdot t g^x = a.

Step 1 is two independent chains of s−1s - 1 squarings, and step 3 performs at most s(s−1)/2s(s-1)/2 multiplications. The work is still O(s2)O(s^2), but the multiplications of each iteration are independent, so their cost is bounded by multiplication throughput instead of latency.

Müller's method#

The cost of Tonelli–Shanks grows with ss. The Cipolla–Lehmer method works in Fn2\mathbb{F}_{n^2} instead, with a cost that does not depend on ss. Müller [Mue2004] gave a version for n≡1(mod4)n \equiv 1 \pmod 4 that needs a single Lucas sequence. For P∈Z/nZP \in \mathbb{Z}/n\mathbb{Z}, let V0=2V_0 = 2, V1=PV_1 = P and Vk+1=PVk−Vk−1V_{k+1} = P V_k - V_{k-1}, so that Vk=αk+α−kV_k = \alpha^k + \alpha^{-k} where α,α−1\alpha, \alpha^{-1} are the roots of X2−PX+1X^2 - PX + 1.

Theorem 4 (Müller). Let n≡1(mod4)n \equiv 1 \pmod 4 be prime, let aa be a nonzero square, and let t≠0t \ne 0 with (at2−4∣n)=−1(a t^2 - 4 \mid n) = -1. With P=at2−2P = a t^2 - 2,

(V(n−1)/4(P)t)2=a.\left(\frac{V_{(n-1)/4}(P)}{t}\right)^2 = a.

Proof. Let u=ta∈Z/nZu = t \sqrt a \in \mathbb{Z}/n\mathbb{Z}, and let ww be a square root of u2−4=at2−4u^2 - 4 = a t^2 - 4 in Fn2\mathbb{F}_{n^2}; it is not in Z/nZ\mathbb{Z}/n\mathbb{Z}. Put β=(u+w)/2\beta = (u + w)/2 and β′=(u−w)/2\beta' = (u - w)/2. Then ββ′=1\beta \beta' = 1, β+β′=u\beta + \beta' = u and β2+β′2=u2−2=P\beta^2 + \beta'^2 = u^2 - 2 = P, so α=β2\alpha = \beta^2 is a root of X2−PX+1X^2 - PX + 1. The Frobenius map fixes uu and sends ww to −w-w, so βn=β′=β−1\beta^n = \beta' = \beta^{-1} and βn+1=1\beta^{n+1} = 1. Hence ε=β(n+1)/2\varepsilon = \beta^{(n+1)/2} satisfies ε2=1\varepsilon^2 = 1 and ε=±1\varepsilon = \pm 1. Now

V(n−1)/4=β(n−1)/2+β−(n−1)/2=εβ−1+εβ=εu=±ta.V_{(n-1)/4} = \beta^{(n-1)/2} + \beta^{-(n-1)/2} = \varepsilon \beta^{-1} + \varepsilon \beta = \varepsilon u = \pm t \sqrt a.
Algorithm 5: Müller

Input: prime n≡1(mod4)n \equiv 1 \pmod 4 and aa.

Output: a candidate root rr, or no answer.

  1. For j=0,1,…,32j = 0, 1, \ldots, 32, let t=2jt = 2^j and test whether (at2−4∣n)=−1(a t^2 - 4 \mid n) = -1; stop at the first success. If none succeeds, give no answer.
  2. P←at2−2P \gets a t^2 - 2.
  3. Compute V=V(n−1)/4(P)V = V_{(n-1)/4}(P) with the ladder (Vm,Vm+1)↦(V2m,V2m+1)(V_m, V_{m+1}) \mapsto (V_{2m}, V_{2m+1}) or (V2m+1,V2m+2)(V_{2m+1}, V_{2m+2}) over the bits of (n−1)/4(n-1)/4, using V2m=Vm2−2V_{2m} = V_m^2 - 2 and V2m+1=VmVm+1−PV_{2m+1} = V_m V_{m+1} - P.
  4. Return r=V/tr = V / t.

Choosing t=2jt = 2^j makes the division by tt in step 4 a sequence of halvings, each a shift and a conditional addition of (n+1)/2(n+1)/2. The Jacobi symbols in step 1 are computed for a−4a - 4 (j=0j = 0) and for cj=4j−1a−1c_j = 4^{j-1} a - 1 (j≥1j \ge 1), because a4j−4=4cja 4^j - 4 = 4 c_j and 4 is a square; they satisfy c1=a−1c_1 = a - 1 and cj+1=4cj+3c_{j+1} = 4 c_j + 3. Each candidate fails with probability about 1/21/2, so giving no answer after 33 candidates is very unlikely; nmod_sqrt then falls back to Tonelli–Shanks.

Each step of the ladder costs one squaring and one independent multiplication, so the latency is about that of one exponentiation. The fixed cost of the Jacobi symbols makes the method pay off only for large ss. FLINT uses it when 6s≥b+1206s \ge b + 120, where bb is the bit length of nn. Since s<bs < b, this happens only for n≥225n \ge 2^{25}, and for 64-bit nn it requires s≥31s \ge 31.

Use in FLINT#

Referenced from#

References#

  • [Coh1996] Cohen, Henri : A course in computational algebraic number theory, Springer, 1996
  • [CraPom2005] R. Crandall and C. Pomerance, Prime Numbers: A Computational Perspective, second edition, Springer (2005).
  • [Atk1992] A. O. L. Atkin, "Probabilistic primality testing", summary by F. Morain, in Algorithms Seminar 1991–1992, INRIA Research Report 1779 (1992), 159–163
  • [Ton1891] A. Tonelli, "Bemerkung über die Auflösung quadratischer Congruenzen", Nachrichten von der Königlichen Gesellschaft der Wissenschaften und der Georg-Augusts-Universität zu Göttingen (1891), 344–346
  • [Sha1973] D. Shanks, "Five number-theoretic algorithms", Proceedings of the Second Manitoba Conference on Numerical Mathematics, Congressus Numerantium 7 (1973), 51–70
  • [Mue2004] S. Müller, "On the computation of square roots in finite fields", Designs, Codes and Cryptography 31 (2004), 301–312, https://doi.org/10.1023/B:DESI.0000015890.44831.e2
Cite this page

The FLINT team, “Square roots modulo a prime,” FLINT: Fast Library for Number Theory, documentation, version 3.7.0-dev, 2026. https://flintlib.org/doc/algorithms/number-theory/sqrt-mod-p.html (generated 2026-11-02).