ll mul(ll a, ll b, ll mod){
a %= mod;
b %= mod;
ll res = 0;
while (b){
if (b&1){
res += a;
if (res >= mod) res -= mod;
}
b >>= 1;
a <<= 1;
if (a >= mod) a -= mod;
}
return res;
}
//使用快速乘法优化快速幂
ll qpow(ll a,ll b,ll mod){
ll ans = 1;
while (b){
if (b&1) ans = mul(ans,a,mod);
a = mul(a,a,mod);
b >>= 1;
}
return ans;
}
//单纯防止数值溢出的快速乘法
ll qmul(ll x,ll y,ll mod){
return (x * y - (ll)(x / (long double)mod * y + 1e-1) * mod + mod) % mod;
}
//米勒罗宾素数测试
//2305843009213693951 (梅森素数)
ll prime[] = {2, 3, 5, 233, 331};
bool Miller_Rabin(ll p){//大数素数判断
if (p<2) return 0;
if (p!=2 && p % 2 ==0) return 0;
ll s = p - 1;
while (! (s & 1)) s >>= 1;
for (int i=0;i<5;++i){
if (p == prime[i]) return 1;
ll t = s, m = qpow(prime[i], s, p);
while (t != p - 1 && m != 1 && m != p - 1){
m = qmul(m, m, p);
t <<= 1;
}
if (m != p - 1 && !(t & 1)) return 0;
}
return 1;
}
Miller Rabin 素数测试 模板
最新推荐文章于 2024-02-01 15:09:49 发布