Skip to main content

SqrtDem

Square Root Modulo P Algorithm

Calculate a(modp)\sqrt{a} \pmod{p} using Shanks' RESSOL algorithm

Understanding Square Roots Modulo Prime

The square root modulo prime problem asks: given integers aa and prime pp, find xx such that x2a(modp)x^2 \equiv a \pmod{p}. Shanks' RESSOL algorithm efficiently solves this when a solution exists:
  1. 1First, we check if aa is a quadratic residue modulo pp using Euler's criterion: a(p1)/21(modp)a^{(p-1)/2} \equiv 1 \pmod{p}
  2. 2For the special case where p1(mod4)p \equiv -1 \pmod{4}, we can use the simple observation: (a(p+1)/4)2a(p1)/2×aa(modp)(a^{(p+1)/4})^2 \equiv a^{(p-1)/2} \times a \equiv a \pmod{p}
  3. 3For p1(mod4)p \equiv 1 \pmod{4}, we factor p1=2smp-1 = 2^s \cdot m where mm is odd
  4. 4We find a quadratic non-residue zz modulo pp (an element where z(p1)/21(modp)z^{(p-1)/2} \equiv -1 \pmod{p})
  5. 5Using the Tonelli-Shanks algorithm, we iteratively reduce the problem until we find the square root
  6. 6The algorithm maintains the invariant that we're solving r2na(modp)r^2 \equiv n \cdot a \pmod{p} where nn has decreasing order of 2