Tonelli-Shanks Algorithm
- •
What it is
- •
An algorithm for computing modular square roots of a quadratic residue mod a prime. When , a closed-form shortcut applies instead of the full algorithm.
- •
- •
When to apply
- •
Given a QR and a prime modulus , you're asked to find with . Check first — if it's 3, skip straight to the shortcut.
- •
- •
Symbols and assumptions
- •
We seek for odd prime and nonzero square . Write with odd; choose a non-square . All multiplications below are modulo .
- •
- •
Math — step by step
- •
- Check separately; otherwise Euler’s criterion must return 1. If , works because .
- •
- For general , initialize , , , . The invariant is ; the goal is to reduce to 1.
- •
- While , find the smallest with . Set , then replace by , by , by , and by .
- •
- The correction preserves and reduces the remaining power-of-two order. At , return and , checking that both square to .
- •
- •
- •
Python
- •
def modular_sqrt(a, p): if p % 4 == 3: return pow(a, (p + 1) // 4, p) raise NotImplementedError("full Tonelli-Shanks needed")
- •
- •
SageMath
- •
Mod(5, 11).sqrt() # 4 (Sage runs full Tonelli-Shanks internally, works for any prime)
- •
- •
- •