Problems > Square Root Modulo a Prime > Editorial

Square Root Modulo a Prime — Solution & Editorial

Back to the Problem

Check Euler's criterion A(P−1)/2 ≡ 1 for solvability. For P ≡ 3 (mod 4), x = A(P+1)/4; otherwise Tonelli–Shanks.

Complexity: O(log2 P)

Watch out: P ≡ 1 (mod 4) genuinely needs Tonelli–Shanks; the (P+1)/4 shortcut only works for P ≡ 3 (mod 4).