Luogu P2303 [SDOI2012] Longge 的问题 题解
题目大意
求 $$\sum_{i=1}^{n}\gcd(i,n)$$
其中 \(1\le n\le 2^{32}\)
题目解析
遇到 \(\gcd\) 的一个普遍讨论套路:枚举 \(\gcd\) 的值,然后改变枚举顺序。
\[\begin{aligned}
& \sum_{i=1}^n \gcd(i,n) \\
= & \sum_{d|n}d\sum_{i=1}^{n}[\gcd(i,n)=d]\\
= & \sum_{d|n}d\sum_{i=1}^{n/d}[\gcd(i,n)=1]\\
= & \sum_{d|n}^{n}d \times \varphi(n/d)
\end{aligned}
\]
然后枚举 \(n\) 的因数就可以了。
复杂度 \(O(\sqrt{n})\)
小提示:十年 OI 一场空,不开 long long 见祖宗
代码:
ll phi(ll x){
ll i,tmp,res; tmp=res=x;
for(i=2;i*i<=x;i++) if(tmp%i==0){ while(tmp%i==0) tmp/=i; res=res/i*(i-1); }
if(tmp!=1) res=res/tmp*(tmp-1);
return res;
}
ll n,ans;
int main(){
n=read(); ll i;
for(i=1;i*i<=n;i++) if(n%i==0){
ans+=(ll)i*phi(n/i);
if(i*i!=n) ans+=(ll)(n/i)*phi(i);
} print(ans); return 0;
}