hdu2138 How many prime numbers 米勒测试
hdu2138 How many prime numbers
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 5 ll prime[6] = {2,3,5,233,331}; 6 ll qmul(ll a, ll b, ll mod) { 7 ll res = 0; 8 while (b) { 9 if (b&1) res = (res+a)%mod; 10 a = (a+a)%mod; 11 b >>= 1; 12 } 13 return res; 14 } 15 ll qpow(ll a, ll b, ll mod) { 16 ll res = 1; 17 while (b) { 18 if (b&1) res = qmul(res,a,mod); 19 a = qmul(a,a,mod); 20 b >>= 1; 21 } 22 return res; 23 } 24 bool Miller_Rabin(ll p) { 25 if (p < 2) return 0; 26 if (p != 2 && p % 2 == 0) return false; 27 ll s = p-1; 28 while (!(s&1)) s >>= 1; 29 for (int i = 0; i < 5; i++) { 30 if (p == prime[i]) return true; 31 ll t = s, m = qpow(prime[i],s,p); 32 while (t != p-1 && m != 1 && m != p-1) { 33 m = qmul(m,m,p); 34 t <<= 1; 35 } 36 if (m != p-1 && !(t&1)) return false; 37 } 38 return true; 39 } 40 int main() { 41 int n; 42 while (~scanf("%d",&n)) { 43 int ans = 0; 44 for (int i = 1; i <= n; i++) { 45 ll x; scanf("%lld",&x); 46 if (Miller_Rabin(x)) ans++; 47 } 48 printf("%d\n",ans); 49 } 50 return 0; 51 }