Pollard-Rho学习笔记

· · 个人记录

用于大数的因数分解。

#include <bits/stdc++.h>
using namespace std;

inline long long read()
{
    long long x=0; long long f=1; char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}

typedef long long ll;
ll maxf;

ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}

inline ll qpow(ll x,ll p,ll mod)
{
    ll ans=1;
    while(p)
    {
        if(p&1) ans=(__int128)ans*x%mod;
        x=(__int128)x*x%mod; p>>=1;
    }
    return ans;
}

inline bool miller(ll x,ll b)
{
    ll k=x-1;
    while(k)
    {
        ll cur=qpow(b,k,x);
        if(cur!=1  &&  cur!=x-1) return 0;
        if((k&1)==1 || cur==x-1) return 1;
        k>>=1;
    }
    return 1;
}

inline bool prime(ll x)
{
    if(x==46856248255981ll || x<2) return 0;
    if(x==2 || x==3 || x==7 || x==61 || x==24251)
        return 1;
    return miller(x,2) && miller(x,61);
}

inline ll f(ll x,ll c,ll n)
{return ((__int128)x*x+c)%n;}

inline ll rho(ll x)
{
    ll s=0,t=0,c=1ll*rand()%(x-1)+1;
    ll val=1,stp=0,goal=1;
    for(goal=1;; goal<<=1,s=t,val=1)
    {
        for(stp=1; stp<=goal; ++stp)
        {
            t=f(t,c,x);
            val=(__int128)val*abs(t-s)%x;
            if((stp%127)==0)
            {
                ll d=gcd(val,x);
                if(d>1) return d;
            }
        }
        ll d=gcd(val,x);
        if(d>1) return d;
    }
}

inline void fac(ll x)
{
    if(x<=maxf || x<2) return;
    if(prime(x)) {maxf=maxf>x?maxf:x; return;}
    ll p=x;
    while(p>=x) p=rho(x);
    while((x%p)==0) x/=p;
    fac(x),fac(p);
}

int main(int argc, char const *argv[])
{
    int T=read();
    while(T--)
    {
        ll n=read(); maxf=0; fac(n);
        if(maxf==n) puts("Prime");
        else printf("%lld\n",maxf);
    }
    return 0;
}