标签:
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12955 Accepted Submission(s): 4490
#include <stdio.h> #include <string.h> #include <math.h> #include <algorithm> using namespace std; long long pow_mod(long long a, long long i, long long n) { if(i==0) return 1%n; long long temp=pow_mod(a, i>>1, n); temp = temp*temp%n; if(i&1) temp = (long long)temp*a%n; return temp; } bool test(int n, int a, int dd) { if(n==2) return true; if(n==a) return true; if( (n&1)==0 ) return false; while(!(dd&1)) dd=dd>>1; int t=pow_mod(a, dd, n); //调用快速幂函数 while((dd!=n-1) &&(t!=1) && (t!=n-1) ) { t = (long long)t*t%n; dd=dd<<1; } return (t==n-1 || (dd&1)==1 ); } bool Miller_Rabin_isPrime(int n) //O(logN) { if(n<2) return false; int a[]={2, 3, 61}; // for(int i=0; i<3; i++) if(!test(n, a[i], n-1) ) return false; return true; } int main() { int n; while(scanf("%d", &n)!=EOF) { int dd; int cnt=0; while(n--) { scanf("%d", &dd); if(Miller_Rabin_isPrime(dd)) cnt++; } printf("%d\n", cnt ); } return 0; }
HDU 2138 How many prime numbers(Miller_Rabin法判断素数 【*模板】 用到了快速幂算法 )
标签:
原文地址:http://www.cnblogs.com/yspworld/p/4343044.html