【HDU2138】How many prime numbers 素数测试

AC通道:http://vjudge.net/problem/HDU-2138

【题目大意】

给n个数判断有几个素数。(每个数<=2^32)

注意多组数据

【题解】

用Rabin_Miller测试跑得飞快。。。

/*************
  HDU 2138
  by chty
  2016.11.5
*************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
ll n,ans;
inline ll read()
{
    ll x=0,f=1;  char ch=getchar();
    while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getchar();}
    while(isdigit(ch))  {x=x*10+ch-'0';  ch=getchar();}
    return x*f;
}
ll fast(ll a,ll b,ll mod) {ll sum=1;for(;b;b>>=1,a=a*a%mod)if(b&1)sum=sum*a%mod;return sum;}//一行快速幂
bool Rabin_Miller(ll p,ll a)
{
    if(p==2)  return 1;
    if(p&1==0||p==1)  return 0;
    ll d=p-1;
    while(!(d&1))  d>>=1;
    ll m=fast(a,d,p);
    if(m==1)  return 1;
    while(d<p)
    {
        if(m==p-1)  return 1;
        d<<=1;
        m=m*m%p;
    }
    return 0;
}
bool isprime(ll x)
{
    static ll prime[9]={2,3,5,7,11,13,17,19,23};
    for(ll i=0;i<9;i++)
    {
        if(x==prime[i])  return 1;
        if(!Rabin_Miller(x,prime[i]))  return 0;
    }
    return 1;
}
int main()
{
    freopen("cin.in","r",stdin);
    freopen("cout.out","w",stdout);
    while(~scanf("%lld",&n))
    {
        ans=0;
        for(ll i=1;i<=n;i++)  
        {
            ll x=read();
            if(isprime(x))  ans++;
        }
        printf("%lld\n",ans);
    }
    return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值