[BZOJ2226][SPOJ5971]LCMSum(莫比乌斯反演)

时间:2021-08-29 13:23:08

2226: [Spoj 5971] LCMSum

Time Limit: 20 Sec  Memory Limit: 259 MB
Submit: 1949  Solved: 852
[Submit][Status][Discuss]

Description

Given
n, calculate the sum LCM(1,n) + LCM(2,n) + .. + LCM(n,n), where
LCM(i,n) denotes the Least Common Multiple of the integers i and n.

Input

The first line contains T the number of test cases. Each of the next T lines contain an integer n.

Output

Output T lines, one for each test case, containing the required sum.

Sample Input

3
1
2
5

Sample Output

1
4
55

HINT

Constraints

1 <= T <= 300000
1 <= n <= 1000000

Source

[Submit][Status][Discuss]

一个比较有用的式子:$$f(n)=\sum_{i=1}^{n}[gcd(i,n)=1]i$$$$f(1)=1\quad f(n)=\lfloor \frac{\varphi(n)*n}{2} \rfloor$$

然后按照套路化式子即可:https://blog.sengxian.com/solutions/bzoj-2226

线性筛WA两次,怎么回事啊?

 #include<cstdio>
#include<algorithm>
#define rep(i,l,r) for (int i=l; i<=r; i++)
typedef long long ll;
using namespace std; const int N=;
int n,T,tot,p[N],phi[N];
bool b[N];
ll g[N]; void pre(){
phi[]=;
for (int i=; i<N; i++){
if (!b[i]) p[++tot]=i,phi[i]=i-;
for (int j=; j<=tot && i*p[j]<N; j++){
int t=i*p[j]; b[t]=;
if (i%p[j]) phi[t]=(p[j]-)*phi[i];
else { phi[t]=p[j]*phi[i]; break; }
}
}
for (int i=; i<N; i++) for (int j=i; j<N; j+=i) g[j]+=1ll*phi[i]*i;
} int main(){
freopen("bzoj2226.in","r",stdin);
freopen("bzoj2226.out","w",stdout);
pre();
for (scanf("%d",&T); T--; ) scanf("%d",&n),printf("%lld\n",(n==)?:((n==)?:(g[n]+)*n/));
return ;
}