# 「SPOJ5971」 LCMSUM - 数论数学

## 题目描述

$\sum_{i=1}^nlcm(i,n)$

$T$ 组数据
$1\le T\le 300000$
$1\le n\le 1000000$

## 题解

### 算法2 （数论）

$\sum_{i=1}^{n-1}lcm(i,n)$
$lcm$ 转化为 $gcd$
$Ans=\sum_{i=1}^{n-1}\frac{in}{gcd(i,n)}$

$Ans=\frac12\cdot 2\sum_{i=1}^{n-1}\frac{in}{gcd(i,n)}$

$Ans=\frac12\cdot(\sum_{i=1}^{n-1}\frac{in}{gcd(i,n)}+\sum_{i=n-1}^1\frac{in}{gcd(i,n)})$

$Ans=\frac12\cdot(\sum_{i=1}^{n-1}\frac{in}{gcd(i,n)}+\sum_{i=n-1}^1\frac{in}{gcd(n-i,n)})$

$Ans=\frac12\cdot(\sum_{i=1}^{n-1}\frac{n^2}{gcd(i,n)})$

$Ans=\frac12n\cdot\sum_{d|n}\frac{n}{d}\cdot \sum_{i=1}^{n}[gcd(i,n)==d]$

$Ans=\frac12n\cdot\sum_{d|n}\frac{n}{d}\cdot \sum_{i=1}^{\frac nd}[gcd(i,\frac nd)==1]$

$Ans=\frac12n\cdot\sum_{d|n}\frac{n}{d}\cdot\phi(\frac{n}d)$

$Ans=\frac12n\cdot\sum_{d|n}d\cdot\phi(d)$

$Ans=(\frac12n\cdot\sum_{d|n}d\cdot\phi(d))-\frac12n$

$Ans=(\frac12n\cdot\sum_{d|n}d\cdot\phi(d))-\frac12n+n\\ =(\frac12n\cdot\sum_{d|n}d\cdot\phi(d))+\frac12n\\ =\frac12n\cdot((\sum_{d|n}d\cdot\phi(d))+1)$

#include <cstdio>
typedef int INT;
#define int long long
#define __R register

const int MAXN=1000005;

int q;
int n;
int f[MAXN],p[MAXN],phi[MAXN];
bool vis[MAXN];

template <typename T>
int ch,fl=0;
while (ch=getchar(),ch<48 || 57<ch) fl^=!(ch^45); x=(ch&15);
while (ch=getchar(),47<ch && ch<58) x=(x<<1)+(x<<3)+(ch&15);
if (fl) x=-x;
}

inline void sieve(){
vis[0]=vis[1]=1; phi[1]=1;
for (__R int i=2;i<MAXN;++i){
if (!vis[i]){
p[++p[0]]=i;
phi[i]=i-1;
}
for (int j=1;j<=p[0] && i*p[j]<MAXN;j++){
vis[i*p[j]]=1;
if (i%p[j]==0){
phi[i*p[j]]=phi[i]*p[j];
break;
} else{
phi[i*p[j]]=phi[i]*(p[j]-1);
}
}
}
for (int i=1;i<MAXN;i++)
for (int j=i;j<MAXN;j+=i)
f[j]+=i*phi[i];
}

inline int solve(int x){
return (f[x]+1)*x>>1;
}

INT main(){
sieve();
}