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\n",ans);
	}
 return 0;
}

  

转载于:https://www.cnblogs.com/heisenberg-/p/6593174.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值