质数的判定 Miller_Rabin

----------- 10^18

 

#include <bits/stdc++.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;
typedef long long ll;
inline int read() {
	int f=1,sum=0;
	char x=getchar();
	for(;(x<'0'||x>'9');x=getchar()) if(x=='-') f=-1;
	for(;x>='0'&&x<='9';x=getchar()) sum=sum*10+x-'0';
	return f*sum;
}

int x_[10]={3,5,7,11,13,17,19,23};


inline ll mul(ll x,ll y,ll mod) {
	ll tmp=x*y-((ll)((long double)x/mod*y+0.5))*mod;
	return tmp<0?tmp+mod:tmp;
}

inline ll qmul(ll x,ll ci,ll mod) {
	ll sum=1;
	for(;ci;ci>>=1,x=mul(x,x,mod))
		if(ci&1) sum=mul(sum,x,mod);
	return sum;
}

inline bool Miller_Rabin(ll n) {
	if(n==1) return 0;
	if(n==2) return 1;
	if(!(n&1)) return 0;
	ll t=n-1;
	int now=0;
	while (!(t&1)) t>>=1,++now;
	
	for(int i = 0; i <= 7; i++){
		if(x_[i]==n) return 1;
		ll x=qmul(x_[i],t,n),y=x;
		for(int j = 1; j <= now; j++) {
			x=mul(x,x,n);
			if(x==1&&!(y==1||y==n-1)) return 0;
			y=x;
		}
		if(x!=1) return 0;
	}
	return 1;
}

int main () {
	//freopen("a.in","r",stdin);
	ll x;
	while (scanf("%lld",&x)==1) {
		if(Miller_Rabin(x)) puts("Y");
		else puts("N");
	}
}

 

posted @ 2018-09-15 09:44  楼主好菜啊  阅读(239)  评论(0编辑  收藏  举报