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

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两次,怎么回事啊?

 1 #include<cstdio>
 2 #include<algorithm>
 3 #define rep(i,l,r) for (int i=l; i<=r; i++)
 4 typedef long long ll;
 5 using namespace std;
 6 
 7 const int N=1000003;
 8 int n,T,tot,p[N],phi[N];
 9 bool b[N];
10 ll g[N];
11 
12 void pre(){
13     phi[1]=1;
14     for (int i=2; i<N; i++){
15         if (!b[i]) p[++tot]=i,phi[i]=i-1;
16         for (int j=1; j<=tot && i*p[j]<N; j++){
17             int t=i*p[j]; b[t]=1;
18             if (i%p[j]) phi[t]=(p[j]-1)*phi[i];
19                 else { phi[t]=p[j]*phi[i]; break; }
20         }
21     }
22     for (int i=1; i<N; i++) for (int j=i; j<N; j+=i) g[j]+=1ll*phi[i]*i;
23 }
24 
25 int main(){
26     freopen("bzoj2226.in","r",stdin);
27     freopen("bzoj2226.out","w",stdout);
28     pre();
29     for (scanf("%d",&T); T--; ) scanf("%d",&n),printf("%lld\n",(n==1)?1:((n==2)?4:(g[n]+1)*n/2));
30     return 0;
31 }

 

posted @ 2018-04-02 17:10  HocRiser  阅读(309)  评论(0编辑  收藏  举报