templates/primitive-root.cpp
compilable
$cat templates/primitive-root
Primitive Root
Find the smallest primitive root (generator) modulo a prime p.
#primitive-root#generator#modular#number-theory#group-theory
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll powerMod(ll a, ll b, ll p) {
ll res = 1;
a %= p;
while (b > 0) {
if (b & 1) {
res = (__int128)res * a % p;
}
a = (__int128)a * a % p;
b >>= 1;
}
return res;
}
ll primitiveRoot(ll p) {
ll phi = p - 1, n = phi;
vector<ll> factors;
for (ll i = 2; i * i <= n; i++) {
if (n % i == 0) {
factors.push_back(i);
while (n % i == 0) {
n /= i;
}
}
}
if (n > 1) {
factors.push_back(n);
}
for (ll g = 2; g <= p; g++) {
bool ok = true;
for (ll q : factors) {
if (powerMod(g, phi / q, p) == 1) {
ok = false;
break;
}
}
if (ok) {
return g;
}
}
return -1;
}46 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Primitive Root
A primitive root modulo is an integer such that its powers generate all nonzero residues mod :
Equivalently, has multiplicative order .
How It Works
When to Use
Properties
Complexity
| Operation | Time | Space |
|---|---|---|
| Factor | ||
| Test one candidate | ||
| Total (worst case) |
Where is the number of distinct prime factors of and is the smallest primitive root (usually very small).