BZOJ 2226: [Spoj 5971] LCMSum
Description
求\(\sum_{i=1}^n[i,n],n\leqslant 10^6,T\leqslant 3\times 10^5\)
Solution
数论..
\(\sum_{i=1}^n[i,n]\)
\(=n\sum_{i=1}^n\frac{i}{(i,n)}\)
\(=n\sum_{d|n}\sum_{i=1}^{\frac{n}{d}}[(i,\frac{n}{d})=1]i\)
后面这个其实可以直接算出来
\(\sum_{i=1}^n[(i,n)=1]i=\sum_{i=1}^ni\sum_{d|i}[d|n]\mu(d)=\sum_{d|n}\mu(d)d\sum_{i=1}^{\frac{n}{d}}i\)
把后面那个式子求和,然后再xjb化一下,就会发现\(n=1\)时为\(1\),其他时候为\(\frac{n\varphi(n)}{2}\)..
然后用欧拉筛统计一下...
复杂度\(O(n\log n)\)
Code
/************************************************************** Problem: 2226 User: BeiYu Language: C++ Result: Accepted Time:7452 ms Memory:28632 kb ****************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; const int N = 1000050; int pr[N],cp; int phi[N],b[N]; LL f[N],h[N]; void pre(int n) { for(int i=2;i<=n;i++) { if(!b[i]) pr[++cp]=i,phi[i]=i-1; for(int j=1;j<=cp && (LL)i*pr[j]<=n;j++) { b[i*pr[j]]=1; if(i%pr[j]) phi[i*pr[j]]=phi[i]*(pr[j]-1); else { phi[i*pr[j]]=phi[i]*pr[j];break; } } } f[1]=1;for(int i=2;i<=n;i++) f[i]=1LL*i*phi[i]/2; for(int i=1;i<=n;i++) for(int j=i;j<=n;j+=i) h[j]+=f[i]; for(int i=1;i<=n;i++) h[i]*=i; // for(int i=1;i<=n;i++) cout<<phi[i]<<" ";cout<<endl; // for(int i=1;i<=n;i++) cout<<f[i]<<" ";cout<<endl; // for(int i=1;i<=n;i++) cout<<h[i]<<" ";cout<<endl; } int T,n; int main() { for(pre(1000000),scanf("%d",&T);T--;) scanf("%d",&n),printf("%lld\n",h[n]); return 0; }