【HDU2138】—How many prime numbers(Miller-Rabin)
二次探测:
对于质数,满足的只有和
直接搬仲爺的博客了
#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ib==ob)?EOF:*ib++;
}
#define gc getchar
inline int read(){
char ch=gc();
int res=0,f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
#define pb push_back
#define ll long long
#define cs const
#define re register
#define pii pair<int,int>
#define fi first
#define se second
int mod;
inline int add(int a,int b){return (a+=b)>=mod?a-mod:a;}
inline void Add(int &a,int b){(a+=b)>=mod?a-=mod:0;}
inline int dec(int a,int b){return a>=b?a-=b:a-b+mod;}
inline void Dec(int &a,int b){(a-=b)<0?a+=mod:0;}
inline int mul(int a,int b){return 1ll*a*b>=mod?1ll*a*b%mod:a*b;}
inline void Mul(int &a,int b){a=mul(a,b);}
inline int ksm(int a,int b,int res=1){
for(;b;b>>=1,Mul(a,a))(b&1)&&(res=mul(res,a));return res;
}
cs int N=10000005,M=N-5;
bool isp[N];
int pr[N],tot;
inline void init(){
for(int i=2;i<=M;i++){
if(!isp[i])pr[++tot]=i;
for(int j=1;j<=tot&&i*pr[j]<=M;j++){
isp[i*pr[j]]=1;
if(i%pr[j]==0)break;
}
}
}
inline bool Miller_Rabin(int x){
mod=x;
if(x<=M)return !isp[x];
if(!(x&1))return false;
if((x%3==0)||(x%5==0)||(x%7==0))return false;
int t=x-1,s=0;
while(!(t&1))t>>=1,s++;
for(int i=1;i<=20&&pr[i]<x;i++){
int k=ksm(pr[i],t),pre=k;
if(x%pr[i]==0)return false;
for(int j=0;j<s;j++){
k=mul(k,k);
if(k==1&&pre!=1&&pre!=x-1)return false;
pre=k;
}
if(k!=1)return false;
}
return true;
}
int n;
int main(){
init();
while(scanf("%d",&n)!=EOF){
int res=0;
for(int i=1;i<=n;i++)if(Miller_Rabin(read()))res++;
cout<<res<<'\n';
}
}