{"id":289,"date":"2026-11-13T12:37:05","date_gmt":"2026-11-13T04:37:05","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-tonelli-shanks-takes-a-square-root-mod-p\/"},"modified":"2026-11-13T21:58:37","modified_gmt":"2026-11-13T13:58:37","slug":"how-tonelli-shanks-takes-a-square-root-mod-p","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-tonelli-shanks-takes-a-square-root-mod-p\/","title":{"rendered":"How Tonelli-Shanks takes a square root mod p"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Tonelli-Shanks<\/strong> computes a square root of a modulo an odd prime p, given that a is a quadratic residue. Write p\u22121 = q\u00b72^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 <strong>O(s\u00b2)<\/strong> modular multiplications after the exponentiations, and s is small for most primes. If the Legendre symbol is \u22121, no square root exists.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Half of the nonzero residues modulo an odd prime are squares, and each of those has two roots, r and p\u2212r. For p \u2261 3 (mod 4) the root is a single exponentiation, a^{(p+1)\/4}. For p \u2261 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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The Legendre symbol (a\/p) = a^{(p\u22121)\/2} mod p is 1 when a is a nonzero residue, \u22121 when it is not, and 0 when p divides a. The algorithm should not be started when the symbol is \u22121.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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\u00b2) correction whose s is the valuation of p\u22121. 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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>If a \u2261 0, return 0. Compute the Legendre symbol. If it is \u22121, report that no root exists. If p \u2261 3 (mod 4), return a^{(p+1)\/4} mod p.<\/li>\n<li>Write p\u22121 = q\u00b72^s with q odd. Find z whose Legendre symbol is \u22121. Set c = z^q mod p, r = a^{(q+1)\/2} mod p, t = a^q mod p, and m = s.<\/li>\n<li>While t is not 1, find the smallest i in 1..m\u22121 such that t^{2^i} \u2261 1. Such an i exists because a is a residue and t has order dividing 2^{m\u22121}.<\/li>\n<li>Set b = c^{2^{m\u2212i\u22121}} mod p. Replace r by r\u00b7b, t by t\u00b7b\u00b2, c by b\u00b2, and m by i.<\/li>\n<li>When t is 1, r is a square root. The other root is p\u2212r.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The special case p \u2261 3 (mod 4) does not need the loop. The general loop needs a prime. Composite moduli are not handled by swapping in Euler&#8217;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\u2212r it keeps.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the modulus is treated as prime without a test<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Run the exponent (p+1)\/4 when p \u2261 1 (mod 4)<\/td>\n<td>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 \u2261 3 (mod 4).<\/td>\n<\/tr>\n<tr>\n<td>Skip the Legendre test<\/td>\n<td>A nonresidue makes the search for i fail or return a number whose square is not a. Test first.<\/td>\n<\/tr>\n<tr>\n<td>Use the algorithm modulo a composite RSA number to avoid factoring<\/td>\n<td>Computing square roots modulo n = p\u00b7q is as hard as factoring n. Tonelli-Shanks does not provide a shortcut there.<\/td>\n<\/tr>\n<tr>\n<td>Return only the smaller root when the caller needed both signs checked<\/td>\n<td>Both r and p\u2212r square to a. A later equation may accept only one of them.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment takes a square root modulo an odd prime. Here p = 13 \u2261 1 (mod 4), so the p \u2261 3 shortcut does not apply and the full correction runs. One square root of 10 is <code>7<\/code>, and 7\u00b2 \u2261 10 (mod 13). The other root is 13\u22127.<\/p>\n\n<pre><code class=\"language-python\">def legendre(a, p):\n    return pow(a, (p - 1) \/\/ 2, p)\n\ndef tonelli(a, p):\n    a %= p\n    if a == 0 or legendre(a, p) != 1:\n        return None\n    if p % 4 == 3:\n        return pow(a, (p + 1) \/\/ 4, p)\n    q, s = p - 1, 0\n    while q % 2 == 0:\n        q \/\/= 2\n        s += 1\n    z = 2\n    while legendre(z, p) != p - 1:\n        z += 1\n    m, c, r, t = s, pow(z, q, p), pow(a, (q + 1) \/\/ 2, p), pow(a, q, p)\n    while t != 1:\n        i, temp = 1, pow(t, 2, p)\n        while temp != 1:\n            temp = pow(temp, 2, p)\n            i += 1\n        b = pow(c, 1 &lt;&lt; (m - i - 1), p)\n        m = i\n        c = pow(b, 2, p)\n        r = r * b % p\n        t = t * c % p\n    return r\n\nroot = tonelli(10, 13)\nassert root is not None and pow(root, 2, 13) == 10\nprint(root)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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&#8217;s modular square root uses that family of algorithms. A square root in the integers is Newton&#8217;s method.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Tonelli-Shanks returns the p \u2261 3 shortcut and the correction loop that handles every other odd prime. <strong>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.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<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\u22121 = q\u00b72^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&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,42],"tags":[],"class_list":["post-289","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-number-theory"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/289","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=289"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/289\/revisions"}],"predecessor-version":[{"id":688,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/289\/revisions\/688"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=289"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=289"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=289"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}