HDU 2138 How many prime numbers (判素数,米勒拉宾算法)

时间:2023-03-09 15:12:18
HDU 2138 How many prime numbers (判素数,米勒拉宾算法)

题意:给定一个数,判断是不是素数。

析:由于数太多,并且太大了,所以以前的方法都不适合,要用米勒拉宾算法。

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstring>
#include <map>
#include <cctype> using namespace std;
typedef long long LL;
const int maxn = 1000 + 5; LL qpow(int a, int b, int r){
LL ans = 1;
LL k = a % r;
while(b){
if(b & 1) ans = (ans * k) % r;
k = (k * k) % r;
b >>= 1;
}
return ans;
} bool miller_rabbin(int n, int a){
int r = 0,s = n-1;
if(!(n % a)) return false;
while(!(s & 1)){ s >>= 1; ++r; } LL k = qpow(a, s, n);
if(1 == k) return true;
for(int j = 0; j < r; ++j, k = k * k % n)
if(k == n-1) return true;
return false;
} bool is_prime(int n){
int tab[] = {2, 3, 5, 7};
for(int i = 0; i < 4; ++i){
if(n == tab[i]) return true;
if(!miller_rabbin(n, tab[i])) return false;
}
return true;
} int main(){
// freopen("in.txt", "r", stdin);
int n, x;
while(~scanf("%d", &n)){
int cnt = 0;
for(int i = 0; i < n; ++i){
scanf("%d", &x);
if(is_prime(x)) ++cnt;
}
printf("%d\n", cnt);
}
}