is a primitive root modulo if its powers generate every residue coprime to — that is, .

Existence

A primitive root modulo exists iff for an odd prime .

In particular, every prime modulus has primitive roots — a substantial fraction, which is why random search finds one quickly.

Finding one

long long primitiveRoot(long long p) {            // p prime
    long long phi = p - 1;
    vector<long long> fac = primeFactors(phi);    // distinct prime factors
    for (long long g = 2; g < p; g++) {
        bool ok = true;
        for (long long q : fac)
            if (powmod(g, phi / q, p) == 1) { ok = false; break; }
        if (ok) return g;
    }
    return -1;
}

Why the test works: divides . If for every prime , then no proper divisor of can be the order, so it must be itself.

The search terminates fast: the smallest primitive root is under GRH, and in practice is a tiny number — for it is almost always below 100.

Cost: dominated by factoring .

Useful primitive roots

ModulusPrimitive rootNote
3the standard NTT prime
3
3
5not NTT-friendly ( only)
37

An NTT-friendly prime has with large, so that is a -th root of unity for every — exactly what the transform needs.

Discrete logarithm

Once is known, every non-zero residue is for a unique , and multiplication becomes addition of exponents. That turns:

Multiplicative problemInto
(discrete root) — a linear congruence
(discrete log)
Order of

This is the number-theoretic analogue of logarithms turning multiplication into addition, and it is the reason primitive roots matter.

Multiplicative order

= the smallest with . It always divides .

long long order(long long a, long long n) {
    long long phi = eulerPhi(n), ord = phi;
    for (long long q : primeFactors(phi))
        while (ord % q == 0 && powmod(a, ord / q, n) == 1) ord /= q;
    return ord;
}

Start from and divide out prime factors while the power still gives 1.

Where it appears

ProblemUse
NTTneed a -th root of unity:
Solving reduce to a linear congruence in the exponent
Length of the decimal period of
Cyclic group structure
Diffie-Hellman, ElGamalthe security rests on the discrete log being hard
Rader’s FFTre-indexes by a primitive root
Counting solutions of solutions if is a -th power residue, else 0

Counting -th power residues

The -th powers modulo form a subgroup of index , so there are exactly of them, and is a -th power iff

For this is the Euler criterion for quadratic residues.

See also: Discrete Logarithm · Discrete Root · Euler Totient