bzoj 2226 LCMSum 欧拉函数

时间:2025-04-22 13:07:37

2226: [Spoj 5971] LCMSum

Time Limit: 20 Sec  Memory Limit: 259 MB
Submit: 1123  Solved: 492
[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

思路:时间复杂度T*sqrt(n);

   小于n并且与n互质的数为phi(k)*k/2;

   1的情况是特例;全部long long会超时。。。卡死我了

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define inf 999999999
#define esp 0.00000000001
const int MAXN=;
int prime[MAXN],cnt;
bool vis[MAXN];
int phi[MAXN];
void Prime(int n)
{
phi[]=;
for(int i=;i<n;i++)
{
if(!vis[i])
{
prime[cnt++]=i;
phi[i]=i-;
}
for(int j=;j<cnt&&i*prime[j]<n;j++)
{
int k=i*prime[j];
vis[k]=;
if(i%prime[j]==)
{
phi[k]=phi[i]*prime[j];
break;
}
else
phi[k]=phi[i]*(prime[j]-);
}
}
}
ll phii(ll n)
{
return (ll)phi[n]*n/;
}
int main()
{
int x,y,z,i,t;
Prime();
scanf("%d",&t);
while(t--)
{
scanf("%d",&x);
ll ans=;
ll gg=sqrt(x);
for(i=;i<=gg;i++)
{
if(x%i==)
ans+=phii(x/i),ans+=phii(i);
}
if(gg*gg==x)
ans-=phii(gg);
printf("%lld\n",(ans+)*x);
}
return ;
}