using ll = longlong; vector<int> prime{2, 3, 5}; ll qpow(ll a, ll b, ll p){ ll ans = 1; while (b) { if (b & 1) ans = ans * a % p; a = a * a % p; b >>= 1; } return ans; } // 如果是long long会发生溢出,则需要在模运算意义下计算快速积
intTwiceDetect(ll a, ll b, ll p){ int r = __builtin_ctz(b); ll d = b >> t; ll x, y; x = y = qpow(a, d, p); while (r--) { y = x * x % p; if (y == 1 && x != 1 && x != p - 1) return1; //是合数返回1 x = y; } return y != 1; }
boolmiller_rabin(ll p){ if (p == 2) returntrue; if (p < 2 || p % 2 == 0) returnfalse; for (int i = 0; i < 3; ++i) { ll base = prime[i]; if (p == base) returntrue; if (TwiceDetect(base, p - 1, p)) return0; } return1; }