51node 1237
$\sum_{i=1}^{n}\sum_{j=1}^{n}gcd(i,j)$
$=\sum_{d=1}^{n}d\sum_{i=1}^{n}\sum_{j=1}^{n}[gcd(i,j)=d]$
$=\sum_{d=1}^{n}d\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{j=1}^{\lfloor\frac{n}{d}\rfloor}[gcd(i,j)=1]$
$=\sum_{d=1}^{n}d\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{j=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{k|i,k|j}\mu(k)$
$=\sum_{d=1}^{n}d\sum_{k=1}^{\lfloor\frac{n}{d}\rfloor}\mu(k)\sum_{i=1}^{\lfloor\frac{n}{kd}\rfloor}\sum_{j=1}^{\lfloor\frac{n}{kd}\rfloor}$
$=\sum_{T=1}^{n}\lfloor\frac{n}{T}\rfloor\lfloor\frac{n}{T}\rfloor\varphi(T)$
$S(n)=\sum_{i=1}^{n}\varphi(i)=\frac{n(n+1)}{2}-\sum_{i=2}^{n}S(\lfloor\frac{n}{i}\rfloor)$
然后分块杜教筛。
1 #include<stdio.h> 2 #define LL long long 3 #define maxn 15000000 4 #define maxm 100001 5 #define mod 1000000007 6 #define inv 500000004 7 int p[1000000],cnt,phi[maxn+1]; 8 int sum_phi[maxm]; 9 LL n; 10 bool book[maxn+1],quest_phi[maxm]; 11 void init() 12 { 13 phi[1]=1; 14 int i; 15 register int j; 16 for(i=2;i<=maxn;i++) 17 { 18 if(!book[i]) 19 { 20 p[++cnt]=i; 21 phi[i]=i-1; 22 } 23 for(j=1;j<=cnt&&i*p[j]<=maxn;j++) 24 { 25 book[i*p[j]]=true; 26 if(i%p[j]==0) 27 { 28 phi[i*p[j]]=phi[i]*p[j]; 29 break; 30 } 31 phi[i*p[j]]=phi[i]*(p[j]-1); 32 } 33 } 34 for(i=2;i<=maxn;i++) 35 { 36 phi[i]+=phi[i-1]; 37 if(phi[i]>=mod) 38 phi[i]-=mod; 39 } 40 } 41 LL query_phi(LL now) 42 { 43 if(now<=maxn) 44 return phi[now]; 45 LL last=n/now; 46 if(quest_phi[last]) 47 return sum_phi[last]; 48 register LL save=now%mod*((now+1)%mod)%mod*inv%mod; 49 LL i,nex; 50 for(i=2;i<=now;i=nex+1) 51 { 52 nex=now/(now/i); 53 save=(save-query_phi(now/i)*((nex-i+1)%mod)%mod+mod)%mod; 54 } 55 quest_phi[last]=true; 56 sum_phi[last]=save; 57 return save; 58 } 59 int main() 60 { 61 init(); 62 scanf("%lld",&n); 63 LL ans=0,j; 64 register LL i; 65 for(i=1,j;i<=n;i=j+1) 66 { 67 j=n/(n/i); 68 ans=(ans+(((i+j)%mod*((j-i+1)%mod)%mod*inv%mod)*(2*query_phi(n/i)-1)%mod)%mod)%mod; 69 } 70 printf("%lld",ans); 71 }