CodeVS1792分解质因数

本文介绍了一种使用 Pollard Rho 方法进行素因数分解的算法实现,并提供了完整的 C++ 代码示例。该算法适用于解决特定类型的数学问题,如大整数的质因数分解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接

  http://codevs.cn/problem/1792/

题解

  pollard rho裸题

代码

//Pollard rho
#include <cstdio>
#include <algorithm>
#include <map>
#include <cstdlib>
#define ll long long
using namespace std;
map<ll,int> ans;
inline ll mult(ll a, ll b, ll p)
{
    ll t=a, ans=0;
    for(;b;b>>=1,t=(t+t)%p)if(b&1)ans=(ans+t)%p;
    return ans;
}
inline ll pow(ll a, ll b, ll p)
{
    ll t=a, ans=1;
    for(;b;b>>=1,t=mult(t,t,p))if(b&1)ans=mult(ans,t,p);
    return ans;
}
inline ll miller_rabin(ll x)
{
    ll a;
    if(x==1)return 0;
    if(x==2)return 1;
    for(ll tim=10;tim;tim--)
    {
        a=rand()%(x-2)+1;
        if(pow(a,x-1,x)!=1)return false;
    }
    return true;
}
ll gcd(ll a, ll b){return !b?a:gcd(b,a%b);}
inline ll pollard_rho(ll n, ll c)
{
    ll i, k, x=rand(), y=x, d;
    for(i=1,k=2;;i++)
    {
        x=(mult(x,x,n)+c)%n;
        d=gcd(x>y?x-y:y-x,n);
        if(d^1)return d;
        if(x==y)return n;
        if(i==k)y=x,k<<=1;
    }
}
void find(ll n, ll c)
{
    if(n==1)return;
    if(miller_rabin(n)){ans[n]++;return;}
    ll p=pollard_rho(n,c);
    for(;p==n;c++)p=pollard_rho(n,c);
    find(p,c), find(n/p,c);
}
int main()
{
    ll n, flag=0; map<ll,int>::iterator it;
    scanf("%lld",&n);
    srand(12345);
    find(n,1);
    printf("%lld=",n);
    for(it=ans.begin();it!=ans.end();it++)
    {
        if(flag==0)printf("%lld",it->first),it->second--,flag=1;
        while(it->second)printf("*%lld",it->first),it->second--;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值