Solve — find all -th roots of .

The prime case, via a primitive root

Let be a primitive root modulo . Write and . Then

which is an ordinary linear congruence.

Algorithm

  1. Find a primitive root modulo .
  2. Compute with baby-step giant-step, .
  3. Solve . Let :
    • if no solution;
    • otherwise there are exactly solutions .
  4. Each gives a root .
vector<long long> discreteRoots(long long k, long long a, long long p) {
    if (a == 0) return {0};
    long long g = primitiveRoot(p);
    long long ia = bsgs(g, a, p);                       // index of a
    if (ia < 0) return {};
    long long d = __gcd(k, p - 1);
    if (ia % d) return {};
    long long mod = (p - 1) / d;
    long long y0 = (__int128)(ia / d) * modinv(k / d, mod) % mod;
    vector<long long> res;
    long long step = powmod(g, mod, p), cur = powmod(g, y0, p);
    for (long long j = 0; j < d; j++) { res.push_back(cur); cur = cur * step % p; }
    sort(res.begin(), res.end());
    return res;
}

Cost: , dominated by the discrete log.

The count

There are either 0 or exactly roots. And is a -th power residue iff

For this is the Euler criterion.

Special cases worth shortcutting

CaseShortcut
exactly one root: no discrete log needed
Tonelli-Shanks or Cipolla,
,
the only root is
the roots of unity

The first row is the one people miss: when is coprime to , the -th root is just a modular exponentiation with the inverse exponent. Check that before reaching for BSGS.

Composite moduli

with :

  1. Factor .
  2. Solve for each prime.
  3. Hensel lift each solution to (the derivative must be a unit — care needed when ).
  4. Recombine every combination with the CRT.

The number of solutions is the product over prime powers, which can be large. needs special handling because is never a unit there.

Cube roots and beyond

Nothing special is needed for or larger — the primitive-root reduction handles all uniformly. The only reason has dedicated algorithms is that quadratic residues are common enough to deserve an method instead of .

ProblemMethod
this page
discrete log
Tonelli-Shanks
Count -th power residues
solve mod , then Hensel
Is a perfect -th power in ?integer -th root, not modular

See also: Primitive Root · Discrete Logarithm · Quadratic Residues