HDU2138 素数判定

HDU2138 给定N个32位大于等于2的正整数 输出其中素数的个数

用Miller Rabin 素数判定法 效率很高 

数学证明比较复杂,略过, 会使用这个接口即可。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long int LL;
LL getPrime(bool notprime[],LL prime[],LL N)
{
 LL tot=0;
 for(LL i=2;i<=N;i++)
   {
    if(!notprime[i]) prime[tot++]=i;
    for(LL j=0;j<tot;j++)
       {
        if(prime[j]*i>N)break;
        notprime[prime[j]*i]=true;
        if(i%prime[j]==0)break;
	   }
   }
 return tot;
}
LL pow_mod(LL n,LL k,LL p)
{
 if(k==0)return 1;
 LL w=1;
 if(k&1)w=n%p;
 LL ans=pow_mod(n*n%p,k>>1,p);
 return ans*w%p;
}
bool Miller_Rabin(LL n,LL a,LL d)
{
 if(n==2)return true;
 if(n==a)return true;
 if(n%a==0)return false;
 if((n&1)==0)return false;
 while(!(d&1))d=d>>1;
 LL t=pow_mod(a,d,n);
 if(t==1)return true;//特别注意!! 
 while((d!=n-1)&&(t!=1)&&(t!=n-1))
 		{
 		 t=(LL)t*t%n;
		 d=d<<1; 
		 
		}

 return (t==n-1||(d&1)==1);
}
bool isPrime(LL n,LL times)                           
{
 if(n<2)return false;
 LL a[4]={2,3,5,7};
 for(LL i=0;i<4;i++){if(!Miller_Rabin(n,a[i],n-1))return false;}
 return true;
}
int main()
{
 LL np;
 while(scanf("%lld",&np)==1)
    {
     LL ans=0,now;
     for(LL i=0;i<np;i++)
        {
		 scanf("%lld",&now);
		 if(isPrime(now,1000000))ans++;
		}
	 printf("%lld
",ans);
	}
 return 0;
}

  

原文地址:https://www.cnblogs.com/heisenberg-/p/6593174.html