POJ1811--miller rabin&pollard rho

好久以前寫過這個題(嗎),但是顯然毫無意義,今天再寫一遍吧。(玄學算法判斷素數和質因數分解。)

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
#define REP(I,ST,ED) for(int I=ST;I<=ED;++I)
#define DREP(I,ST,ED) for(int I=ST;I>=ED;--I)
typedef long long ll;
namespace Math{
	ll gcd(ll a,ll b){
		if(b==0)return a;
		else return gcd(b,a%b);
	}
	ll ksc(ll x,ll y,ll p){
		if(x<y)swap(x,y);
		ll res=0;
		while(y){
			if(y&1)(res+=x)%=p;
			(x+=x)%=p,y>>=1;
		}return res;
	}
	bool check(ll x,ll p,ll times,ll t){
		ll res=1;
		while(times){
			if(times&1)res=ksc(res,x,p);
			x=ksc(x,x,p),times>>=1;
		}REP(k,1,t){
			if((res==1)||(res==p-1))return 1;
			else if((res=ksc(res,res,p))==1)return 0;
		}return (t==0)&(res==1);
	}
	bool miller_rabin(ll p){
		ll times=p-1,t=0;
		while(!(times&1))times>>=1,++t;
		REP(k,1,5)
			if(!check(rand()%(p-1)+1,p,times,t))return 0;
		return 1;
	}
	ll pollard_rho(ll p){
		if(miller_rabin(p))return p;
		while(1){
			ll b=rand()%(p-1)+1,x=rand()%(p-1)+1,y=x,t;
			for(int i=1,k=1;;++i){
				y=(ksc(y,y,p)+b)%p;
				t=gcd((y-x+p)%p,p);
				if((t>1)&&(t<p))return min(pollard_rho(t),pollard_rho(p/t));
				if(x==y)break;
				if(i==k)k<<=1,x=y;
			}
		}
	}
	void solve(ll p){
		ll ans=pollard_rho(p);
		if(ans==p)puts("Prime");
		else printf("%lld\n",ans);
	}
}	
int main(){
#ifndef ONLINE_JUDGE
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
#endif
	srand('j'+'m');
	int T;
	scanf("%d",&T);
	while(T--){
		ll x;
		scanf("%lld",&x);
		Math::solve(x);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章