跳到正文

题解

题解 P2303 【[SDOi2012]Longge的问题】

ycyaw约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年4月8日
收录
2026年1月9日
更新
2026年11月12日
篇幅
约 2 分钟
题目
P2303

版本

  1. v2当前
  2. v1

好水的蓝题啊,少数没有看题解做的题

题面简洁明了:求∑i=1ngcd(i,n)\sum\limits_{i=1}^{n}gcd(i,n)

设gcd(i,n)=dgcd(i,n)=d,则gcd(i/d,n/d)=1gcd(i/d,n/d)=1

dd显然就是nn的因数

我们对于每个dd,要求有多少ii使得gcd(i/d,n/d)=1gcd(i/d,n/d)=1,设求出有xx个ii,那么对答案的贡献就是d×xd \times x。为什么是这些贡献?很显然,这些ii与nn的gcdgcd就是dd,共xx个这样的ii,所以是d×xd \times x。

因为满足gcd(i/d,n/d)=gcd(i/d,n/d)=1的i/di/d的个数就是与n/dn/d互质的数,每个i/di/d又对应一个ii,个数就是φ(n/d)φ(n/d)。前面说了dd是nn的因数,我们枚举所有因数,累加φ(n/d)φ(n/d)即可。

对于每个φ(n/d)φ(n/d),n\sqrt{n}求即可。

代码:

C++
#include<bits/stdc++.h>
#define ts cout<<"ok"<<endl
#define oo (1e18)
#define int long long
#define LL unsigned long long
#define hh puts("")
using namespace std;
int ans,n;
inline int read(){
    int ret=0,ff=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-') ff=-1;ch=getchar();}
    while(isdigit(ch)){ret=(ret<<3)+(ret<<1)+(ch^48);ch=getchar();}
    return ret*ff;
}
inline int getphi(int x){
    int res=x;
    for(int i=2;i*i<=x;i++){
        if(x%i==0){
            res=res/i*(i-1);
            while(x%i==0) x/=i;
        }
    }
    if(x>1) res=res/x*(x-1);
    return res;
}
signed main(){
    n=read();
    int sq=sqrt(n);
    for(int i=1;i<=sq;i++){
        if(n%i==0){
            ans+=getphi(n/i)*i;
            if(i*i!=n) ans+=getphi(i)*(n/i);
        }
    }
    printf("%lld",ans);
    return 0;
}
原文
存档评论8 条抓取于