唯一分解之Pollard-Rho算法

一般分解是\sqrt{x}的复杂度,那么Pollard-Rho复杂度大概是\sqrt{\sqrt{x}},嗯就是x的四分之一次方,也就是说即使是longlong 的极限1e18,也能1s内跑的出来(18/4 = 4.5)

原理:

对于一个大整数n,我们取任意一个数x是n的质因数的几率很小,

如果取两个数x1以及x2使得它们的差是n的因数,那么几率就提高了,

如果取x1以及x2使得gcd((x1−x2),n)>1的概率就更高了。(概率的增加是因为组合数增加了)

这就是Pollard-Rho算法的主要思想。

我们随机x1,计算x2,(x[i] = (x[i-1]*x[i-1]%n+c)%n,c是一个自己定的常数 ),然后递归求解

Miller_Rabbin来判断是否是素因子(单纯的因子的话递归分解它,素因子丢进答案的vector里)

 

 

poj1811,这是一道裸题,输出最小的素因子,本身是素数的话输出Prime

下面是代码

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 1e5+7;
vector<ll> vec;
ll MMul(ll x,ll y,ll mod,ll ans = 0){
    return (x * y - (long long)(x / (long double)mod * y + 1e-3) *mod + mod) % mod;
}
ll MExp(ll a,ll b,ll mod,ll ans = 1){
    for(a %= mod;b;b>>=1){
        if(b&1)ans = MMul(ans,a,mod);
        a = MMul(a,a,mod);
    }
    return ans;
}
bool Miller_Rabin(ll n,ll u = 0,int t = 0,int s = 10){
    if(n == 2)return true;
    if(n<2||!(n&1))return false;/// <2 || %2==0
    for(t = 0,u = n-1;!(u&1);t++,u>>=1);///n-1=u*2^t
    while(s--){/// s time
        ll a = rand()%(n-1)+1;
        ll x = MExp(a,u,n);///a^u
        for(int i=0;i<t;i++){
            ll y = MMul(x,x,n);/// (a^u)^2
            if(y == 1&&x!=1&&x!=n-1)
                return false;
            x = y;
        }
        if(x!=1)return false;/// (a^p-1)%p != 1
    }
    return true;
}
ll Pollard_Rho(ll n, int c){
    ll i = 1, k = 2, x = rand()%(n-1)+1, y = x;
    while(true){
        i++;
        x = (MMul(x, x, n) + c)%n;
        ll p = __gcd((y-x+n)%n,n);
        if(p != 1 && p != n) return p;
        if(y == x) return n;
        if(i == k){
            y = x;
            k <<= 1;
        }
    }
}
void Find(ll n, int c){
    if(n == 1) return;
    if(Miller_Rabin(n)){
        vec.push_back(n);
        return;
    }
    ll p = n, k = c;
    while(p >= n) p = Pollard_Rho(p, c--);
    Find(p, k);
    Find(n/p, k);
}
int main(){
    int t;
    cin>>t;
    while(t--){
        ll k;
        cin>>k;
        if(Miller_Rabin(k)){cout<<"Prime"<<endl;continue;}
        vec.clear();
        Find(k,2333);
        sort(vec.begin(),vec.end());
        cout<<vec[0]<<endl;
    }
    return 0;
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值