欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【模板】MillerRabin素数测试

程序员文章站 2024-01-20 22:15:10
...

参考题目:HDU2138


解析:

模板题解析万年不更就是我zxyoizxyoizxyoi


代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define re register
#define gc getchar
#define pc putchar
#define cs const

inline
int getint(){
	re int num;
	re char c;
	while(!isdigit(c=gc()));num=c^48;
	while(isdigit(c=gc()))num=(num<<1)+(num<<3)+(c^48);
	return num;
}

ll prime[10]={2,3,7,61,24251};

ll quickpow(ll a,ll b,ll mod){
	ll res=1;
	while(b){
		if(b&1)res=res*a%mod;
		a=a*a%mod;
		b>>=1;
	}
	return res;
}

bool Miller_Rabin(ll x){
	if(x==2)return true;
	if(x<2||!(x&1))return false;
	ll bit,tmp=x-1;
	while(0==(tmp&1))tmp>>=1,++bit; 
	for(int re i=0;i<5&&prime[i]<x;++i){
		ll a=prime[i];
		ll b=quickpow(a,tmp,x);
		for(int re j=1;j<=bit;++j){
			ll k=b*b%x;
			if(k==1&&b!=1&&b!=x-1)return false;
			b=k;
		}
		if(b!=1)return false;
	}
	return true;
}

int n;
ll x;
int ans;
signed main(){
	while(~scanf("%d",&n)){
		ans=0;
		for(int re i=1;i<=n;++i){
			x=getint();
			if(Miller_Rabin(x))++ans;
		}
		cout<<ans<<endl;
	}
	return 0;
}