bzoj 4802: 欧拉函数 大整数分解

该博客主要探讨了如何计算欧拉函数φ(n),针对不超过10^18的大整数,提出了使用Pollard Rho算法进行质因数分解的方法。通过质因数分解来解决大整数的欧拉函数问题。

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

题意

φ(n)
n<=1e18

分析

直接用pollard rho对n分解质因数就好了。

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

typedef long long LL;

LL prime[9]={2,3,5,7,11,13,17,19,23},n,a[105];
int a1;

LL gcd(LL x,LL y)
{
    if (!y) return x;
    else return gcd(y,x%y);
}

LL mul(LL x,LL y,LL mo)
{
    LL tmp=(x*y-(LL)((double)x*y/mo+0.1)*mo)%mo;
    if (tmp<0) tmp+=mo;
    return tmp;
}

LL ksm(LL x,LL y,LL mo)
{
    LL ans=1;
    while (y)
    {
        if (y&1) ans=mul(ans,x,mo);
        x=mul(x,x,mo);y>>=1;
    }
    return ans;
}

bool MR(LL n)
{
    if (n==2) return 1;
    if (n%2==0) return 0;
    int lg=0;LL w=n-1;
    while (w%2==0) lg++,w/=2;
    for (int i=0;i<9;i++)
    {
        if (n==prime[i]) return 1;
        LL x=ksm(prime[i],w,n);
        if (x==1||x==n-1) continue;
        for (int j=1;j<=lg;j++)
        {
            LL y=mul(x,x,n);
            if (x!=1&&x!=n-1&&y==1) return 0;
            x=y;
        }
        if (x!=1) return 0;
    }
    return 1;
}

LL rho(LL n)
{
    LL c=rand()*rand()%(n-1)+1,x1=rand()*rand()%n,x2=x1,k=2,p=1;
    for (int i=1;p==1;i++)
    {
        x1=(mul(x1,x1,n)+c)%n;
        if (x1==x2) return 1;
        p=gcd(n,abs(x1-x2));
        if (i==k) k<<=1,x2=x1;
    }
    return p;
}

void divi(LL n)
{
    if (n==1) return;
    if (MR(n))
    {
        a[++a1]=n;return;
    }
    LL p=1;
    while (p==1) p=rho(n);
    divi(p);divi(n/p);
}

int main()
{
    scanf("%lld",&n);
    divi(n);
    sort(a+1,a+a1+1);
    a1=unique(a+1,a+a1+1)-a-1;
    for (int i=1;i<=a1;i++) n=n/a[i]*(a[i]-1);
    printf("%lld",n);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值