Miller-Rabin素性测试
【例题】How many prime numbers
k个数选取:一般选取8个素数(zhx选的{2,3,5,7,11,13,17,37},他说这八个数判定long long以内的素数不会出错)
我们把
若
那么,
#include <iostream>
using LL = long long;
int qmod(LL x, int y, int n) {
int ans = 1;
while (y) {
if (y & 1) ans = ans*x % n;
x = x*x % n, y >>= 1;
}
return ans;
}
bool miller(int n) {
if (n<2 || (n>2&&n%2==0)) return false;
int y = n - 1, num[8] = {2,3,5,7,11,13,17,37};
for (int i = 0; i < 8; ++i)
if (n == num[i]) return true;
while (not (y&1)) y >>= 1;
for (int i = 0; i < 8; ++i) {
LL u = y, x = qmod(num[i], y, n);
//基于费马定理a^(n-1) mod n = 1,将n-1表示成(2^s)*d的形式,d为奇数
//若n为素数,x^2模n为1,那么由于素数的原子性,n必整除(x-1)(x+1)的其中一个,否则即为合数
//如果有一个num[i]未通过测试,就一定不是素数
while (u<n-1 && x!=1 && x!=n-1) {
x = x * x % n;
u <<= 1;
}
if (x!=n-1 && u%2==0) return false;
}
return true;
}
int main() {
int kases, n, cnt;
while (~scanf("%d", &kases)) {
cnt = 0;
while (kases--) {
scanf("%d", &n);
if (miller(n)) ++cnt;
}
printf("%d\n", cnt);
}
return 0;
}