标签:算法
PS: 素数判定问题。
#include <iostream> #include <cstdio> #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 tmp = pow_mod(a, i>>1, n); // int tmp. WA. tmp = tmp*tmp%n; if(i&1) tmp = (long long)tmp*a%n; return tmp; } bool test(int n, int a, int d) { if(n==2) return true; if(n==a) return true; if((n&1)==0) return false; while(!(d&1)) d = d>>1; int t = pow_mod(a, d, n); while((d!=n-1) && (t!=1) && (t!=n-1)) { t = (long long)t*t%n; d = d << 1; } return (t==n-1 || (d&1)==1); } bool isPrime(int n) { if(n<2) return false; // int a[] = {2, 3 , 5, 7, 11, 13, 17}; int a[] = {2, 3, 5}; for(int i = 0; i <= 2; i++) { if(!test(n, a[i], n-1)) return false; } return true; } int main() { int n, t, cnt; while(scanf("%d", &n)!=EOF) { int *p = new int[n+5]; for(int i = 0; i < n; i++) { scanf("%d", &t); p[i] = t; } cnt = 0; for(int i = 0; i < n; i++) { if(isPrime(p[i])) cnt++; } printf("%d\n", cnt); } return 0; }
HDU2138 How many prime numbers
标签:算法
原文地址:http://blog.csdn.net/achiberx/article/details/24652505