poj 2480 积性函数+欧拉函数

题目传送门

1. 欧拉函数 204ms

//积性函数
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
typedef long long LL;
LL euler(LL n)
{
    LL res=n;
    for(int i=2;(LL)i*i<=n;i++)
    {
        if(n==1) break;
        if(n%i==0) {
            res/=i;
            res*=(i-1);
            while(n%i==0) n/=i;
        }
    }
    if(n!=1) {
        res/=n;
        res*=(n-1);
    }
    return res;
}
int main()
{
    LL n;
    while(scanf("%lld",&n)==1)
    {
        LL ans=0;
        for(int i=1;(LL)i*i<=n;i++)
        {
            if(n%i==0) {
                ans+=euler(n/i)*i;
                if(i!=n/i) ans+=euler(i)*(n/i);
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}

2. gcd(i,m*n)=gcd(i,m)*gcd(i,n)   当n和m互质的时候成立,积性函数的和函数依旧为积性函数,利用积性函数的性质解题,时间为32ms

//唯一分解定理+积性函数
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int maxn=100+5;
int fac[maxn],num[maxn];
int cnt;
LL pow(LL a,LL b)
{
    LL res=1;
    while(b)
    {
        if(b&1) res=res*a;
        b>>=1;
        a=a*a;
    }
    return res;
}
int main()
{
    LL n;
    while(scanf("%lld",&n)==1)
    {
        LL ans=1;
        cnt=0;
        //唯一分解
        for(int i=2;(LL)i*i<=n;i++)
        {
            if(n==1) break;
            if(n%i==0) {
                fac[cnt]=i;
                num[cnt]=0;
                while(n%i==0) {
                    n/=i;
                    num[cnt]++;
                }
                cnt++;
            }
        }
        if(n!=1) {
            fac[cnt]=n;
            num[cnt]=1;
            cnt++;
        }
        LL temp;
        for(int i=0;i<cnt;i++)
        {
            temp=(fac[i]-1)*pow(fac[i],num[i]-1)*num[i]+pow(fac[i],num[i]);
            ans*=temp;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值