Purpose: Compute a modular square root with in multiplications — with no dependence on the 2-adic valuation of , unlike Tonelli-Shanks.

Algorithm

  1. Verify is a quadratic residue: .
  2. Find such that is a non-residue. Try ; roughly half of all work, so this takes attempts on average.
  3. Work in the quadratic field extension — i.e. treat numbers as pairs with .
  4. The answer is

    The result is guaranteed to have zero -component.

Code

long long P, W;                                   // modulus and omega^2
 
struct F2 { long long a, b; };                    // a + b*omega
 
F2 mul(F2 x, F2 y) {
    return { (x.a * y.a + W % P * (x.b * y.b % P)) % P,
             (x.a * y.b + x.b * y.a) % P };
}
 
long long cipolla(long long a, long long p) {
    P = p; a %= p; if (a < 0) a += p;
    if (a == 0) return 0;
    if (powmod(a, (p - 1) / 2, p) != 1) return -1;      // not a residue
 
    long long t = 1;
    while (powmod(((t * t - a) % p + p) % p, (p - 1) / 2, p) != p - 1) t++;
    W = ((t * t - a) % p + p) % p;
 
    F2 r{1, 0}, base{t, 1};
    long long e = (p + 1) / 2;
    while (e) { if (e & 1) r = mul(r, base); base = mul(base, base); e >>= 1; }
    return r.a;                                          // r.b is provably 0
}

Paradigm

Field extension. The trick is to leave , do the work where the answer exists trivially, and come back.

Complexity

  • Time: multiplications in (each is 3-4 multiplications in ), plus expected tries for
  • Space:

Why It Works

Since is a non-residue, and is a genuine field of order . In the Frobenius map is an automorphism fixing exactly , and . Therefore

So satisfies . And lies in because implies is fixed by Frobenius. ∎

Cipolla vs Tonelli-Shanks

CipollaTonelli-Shanks
Time mults, no dependence worst case (with large)
Arithmeticneeds stays in
Code lengthshorter once the extension struct existslonger control flow
When not needed — just not needed either

In competitive programming the moduli are usually small enough that either works; Tonelli-Shanks is more commonly written, Cipolla is preferable when has a large power of 2 (as it does for NTT-friendly primes like ).

Variants / Use Cases

  • Quadratic residues — the underlying theory
  • Discrete roots — the -th root generalisation
  • Hensel lifting — extend a root mod to mod
  • Elliptic curve point decompression — recovering from requires a modular square root