【Pollard Rho模板】【bzoj 3667】: Rabin-Miller算法

http://www.lydsy.com/JudgeOnline/problem.php?id=3667


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
#define rep(i,l,r) for(int i=(l),_=(r);i<=_;i++)
#define per(i,r,l) for(int i=(r),_=(l);i>=_;i--)
#define MS(arr,x) memset(arr,x,sizeof(arr))
#define INE(i,u) for(int i=head[u];~i;i=e[i].next)
#define LL long long
inline const LL read()
{LL r=0,k=1;char c=getchar();for(;c<'0'||c>'9';c=getchar())if(c=='-')k=-1;
for(;c>='0'&&c<='9';c=getchar())r=r*10+c-'0';return k*r;}

LL n,mx;

LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
LL mul(LL a,LL b,LL p)
{
	a%=p; b%=p;
	LL t=(a*b-(LL)((double)a/p*b+0.5)*p);
	return t<0?t+p:t;
}
LL pow(LL a,LL b,LL p){LL t=1;for(;b;b>>=1,a=mul(a,a,p))if(b&1)t=mul(t,a,p);return t;}
bool check(LL a,LL n,LL r,LL s)
{
	LL t=pow(a,r,n),p=t;
	rep(i,1,s)
	{
		t=mul(t,t,n);
		if(t==1&&p!=1&&p!=n-1) return 1;
		p=t;
	}
	return t!=1;
}
bool MR(LL n)
{
	if(n<2) return 0;
	if(n==2 || n==3) return 1;
	if(n%6!=1 && n%6!=5) return 0;
	LL r=n-1,s=0;
	while(!(r&1)) r>>=1,s++;
	rep(i,0,9) if(check(rand()%(n-1)+1,n,r,s)) return 0;
	return 1;
}
LL rho(LL n,LL c)
{
	LL k=2,x=rand()%n,y=x,p=1;
	for(LL i=1;p==1;i++)
	{
		x=(mul(x,x,n)+c)%n;
		p=abs(x-y);
		p=gcd(n,p);
		if(i==k) y=x,k<<=1;
	}
	return p;
}
void cal(LL n)
{
	if(n==1) return;
	if(MR(n))
	{
		mx=max(mx,n);
		return;
	}
	LL t=n;
	while(t==n) t=rho(n,rand()%(n-1)+1);
	cal(t); cal(n/t);
}

void input()
{
	n=read(); mx=0;
}
void solve()
{
	cal(n);
	if(mx==n) puts("Prime");
	else printf("%lld\n",mx);
}

int main()
{
    //freopen("_.in","r",stdin); freopen("_.in","w",stdout);
    rep(T,1,read())
    input(),solve();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值