This documentation is automatically generated by competitive-verifier/competitive-verifier
#include "src/math/proot.hpp"// 时间复杂度瓶颈在质因数分解.
#include "pollardrho.hpp"
ll proot(ll p) {
if (p == 2) return 1;
ll phi = p - 1;
auto factors = breakdown(phi);
factors.erase(unique(ALL(factors)), factors.end());
for (ll ret = 2; ret <= p; ret++) {
bool ok = 1;
for (int i = 0; i < int(factors.size()) && ok; i++) {
if (pow_mod_ll(ret, phi / factors[i], p) == 1) {
ok = 0;
break;
}
}
if (ok) return ret;
}
return -1;
}
#line 1 "src/math/proot.hpp"
// 时间复杂度瓶颈在质因数分解.
#line 1 "src/math/pollardrho.hpp"
// 时间复杂度: 期望 $\mathcal{O}(n^{1/4})$
#line 1 "src/math/millerrabin.hpp"
// 时间复杂度: $\mathcal{O}(k \log n)$,目前 $k = 9$ 足以判定 $64$ 位整数.
#line 1 "src/math/pow_mod_ll.hpp"
ll pow_mod_ll(ll a, ull n, ll p) {
ll ret = 1;
for (; n; n /= 2) {
if (n & 1) ret = i128(ret) * a % p;
a = i128(a) * a % p;
}
return ret;
}
#line 3 "src/math/millerrabin.hpp"
bool isprime(ll n) {
if (n < 2) return 0;
int s = __builtin_ctzll(n - 1);
ll d = (n - 1) >> s;
for (int a : {2, 3, 5, 7, 11, 13, 17, 19, 23}) {
if (a == n) return 1;
ll x = pow_mod_ll(a, d, n);
if (x == 1 || x == n - 1) continue;
bool ok = 0;
for (int i = 0; i + 1 < s; i++) {
x = i128(x) * x % n;
if (x == n - 1) {
ok = 1;
break;
}
}
if (!ok) return 0;
}
return 1;
}
#line 3 "src/math/pollardrho.hpp"
ll pollard_single(ll n) {
if (n % 2 == 0) return 2;
if (isprime(n)) return n;
ll st = 0;
auto f = [&](ll x) -> ll { return (i128(x) * x % n + st) % n; };
while (true) {
st++;
ll x = st, y = f(x);
while (true) {
ll p = gcd(y - x + n, n);
if (p == 0 || p == n) break;
if (p != 1) return p;
x = f(x), y = f(f(y));
}
}
}
vector<ll> breakdown(ll n) {
if (n == 1) return {};
ll x = pollard_single(n);
if (x == n) return {n};
auto l = breakdown(x), r = breakdown(n / x);
l.insert(l.end(), ALL(r)), sort(ALL(l));
return l;
}
#line 3 "src/math/proot.hpp"
ll proot(ll p) {
if (p == 2) return 1;
ll phi = p - 1;
auto factors = breakdown(phi);
factors.erase(unique(ALL(factors)), factors.end());
for (ll ret = 2; ret <= p; ret++) {
bool ok = 1;
for (int i = 0; i < int(factors.size()) && ok; i++) {
if (pow_mod_ll(ret, phi / factors[i], p) == 1) {
ok = 0;
break;
}
}
if (ok) return ret;
}
return -1;
}