1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 #include<algorithm> 6 #include<cmath> 7 #include<cstdlib> 8 #include<ctime> 9 #define lson l, m, rt<<1 10 #define rson m+1, r, rt<<1|1 11 #define INF 0x3f3f3f3f 12 typedef long long LL; 13 using namespace std;/* ************************************************* 14 * Miller_Rabin 算法进行素数测试 15 * 速度快,可以判断一个 < 2^63 的数是不是素数 16 * 17 **************************************************/ 18 const int S = 8; 19 LL mult_mod(LL a,LL b,LL c) 20 { 21 a %= c; 22 b %= c; 23 LL ret = 0; 24 LL tmp = a; 25 while(b) 26 { 27 if(b & 1) 28 { 29 ret += tmp; 30 if(ret > c)ret -= c; 31 } 32 tmp <<= 1; 33 if(tmp > c)tmp -= c; 34 b >>= 1; 35 } 36 return ret; 37 } 38 LL pow_mod(LL a,LL n,LL mod) 39 { 40 LL ret = 1; 41 LL temp = a%mod; 42 while(n) 43 { 44 if(n & 1)ret = mult_mod(ret,temp,mod); 45 temp = mult_mod(temp,temp,mod); 46 n >>= 1; 47 } 48 return ret; 49 } 50 bool check(LL a,LL n,LL x,LL t) 51 { 52 LL ret = pow_mod(a,x,n); 53 LL last = ret; 54 for(int i = 1;i <= t;i++) 55 { 56 ret = mult_mod(ret,ret,n); 57 if(ret == 1 && last != 1 && last != n-1)return true; 58 last = ret; 59 } 60 if(ret != 1)return true; 61 else return false; 62 } 63 bool MiLLer_Rabin(LL n) 64 { 65 if( n < 2)return false; 66 if( n == 2)return true; 67 if( (n&1) == 0)return false; 68 LL x = n - 1; 69 LL t = 0; 70 while( (x&1)==0 ){x >>= 1; t++;} 71 srand(time(NULL)); 72 for(int i = 0;i < S;i++) 73 { 74 LL a = rand()%(n-1) + 1; 75 if( check(a,n,x,t) ) 76 return false; 77 } 78 return true; 79 } 80 int main() 81 { 82 LL n, m; 83 while(cin >> n){ 84 LL cnt=0; 85 for(int i = 0; i < n; i++){ 86 cin >> m; 87 if(MiLLer_Rabin(m)) 88 cnt++; 89 } 90 cout << cnt << endl; 91 } 92 }
Miller Rabin素数检测
猜你喜欢
转载自www.cnblogs.com/Surprisezang/p/9059520.html
今日推荐
周排行