Miller-Rabin,Pollard-Rho(BZOJ3667)

时间:2023-03-09 15:10:14
Miller-Rabin,Pollard-Rho(BZOJ3667)

裸题直接做就好了。

#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std; typedef long long ll;
const int p[]={,,,,,,,,};
int T;
ll n,mx; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll mul(ll a,ll b,ll p) {
ll r=a*b-(ll)((long double)a/p*b+1e-)*p;
return r<?r+p:r;
}
ll qp(ll a,ll b,ll p) {
ll r=;
for(;b;b>>=,a=mul(a,a,p)) if(b&) r=mul(r,a,p);
return r;
}
bool chk(ll a,ll n,ll r,ll s) {
ll x=qp(a,r,n),pre=x;
for(int i=;i<=s;i++,pre=x) {
x=mul(x,x,n);
if(x==&&pre!=&&pre!=n-) return ;
}
return x==;
}
bool mr(ll n) {
ll r=n-,s=;
while(!(r&)) r>>=,s++;
for(int i=;i<;i++) {
if(p[i]==n) return ;
if(!chk(p[i],n,r,s)) return ;
}
return ;
}
ll po(ll n,ll a) {
for(ll i=,k=,x=rand()%n,y=x;;i++) {
x=(mul(x,x,n)+a)%n;
if(gcd(n,abs(y-x))^) return gcd(n,abs(y-x));
if(i==k) y=x,k<<=;
}
}
void sol(ll n) {
if(n==) return;
if(mr(n)) {mx=max(mx,n); return;}
ll t=n;
while(t==n) t=po(n,rand()%n);
sol(t),sol(n/t);
} int main() {
srand();
scanf("%d",&T);
while(T--) {
scanf("%lld",&n),mx=,sol(n);
if(mx==n) puts("Prime"); else printf("%lld\n",mx);
}
return ;
}