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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值