spoj LCMSUM sigma(lcm(i,n));

时间:2022-07-14 20:39:39

Problem code: LCMSUM

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.

Example

Sample Input :
3
1
2
5

Sample Output :
1
4
55

Constraints

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

题意:sigma(lcm(i,n)) ; 1<=i<=n

思路:题意倒是很简单,有类似的题目sigma(gcd(i,n)) ;1<=i<=n;

    一看就是果然是同类型的。

gcd(i,n)的题目 http://www.cnblogs.com/tom987690183/p/3247439.html

这个是求lcm()最小公倍数.

同样的思路,我们枚举gcd() = d 则在[ 1 , n ]中与n最大公约数为d的值有euler(n/d)个.

这些数的和为euler(n/d)*n/2;  我们知道lcm = x*n/(gcd(x,n)) = > x*n/d ;

因为与n gcd() = d的数字为x1,x2,x3....

根据lcm = x*n/(gcd(x,n)) 可以得到 (n/d)*(x1+x2+x3...) => [euler(n/d)*n/2]*(n*d);

这里需要注意的是当gcd(i,n) = n的时候,用euler(n)*n/2算的时候是不对的,就特判吧。

这样的思路,我们就可以试一下打欧拉表opl[ ],需要时间o(N);

然后对于n,要用sqrt(n)的时间。

T*sqrt(n)+o(N) = 3^8+10^6.果断超时。以为能ac,吼吼。

 #include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef long long LL; const int maxn = 1e6+;
int opl[maxn];
void init()
{
for(int i=;i<maxn;i++) opl[i] = i;
for(int i=;i<maxn;i++)
{
if(opl[i]==i) opl[i] = i-;
else continue;
for(int j=i+i;j<maxn;j=j+i)
opl[j] = opl[j]/i*(i-);
}
}
int main()
{
int T;
LL n;
init();
scanf("%d",&T);
while(T--)
{
scanf("%lld",&n);
LL sum = ;
for(LL i=;i*i<=n;i++)
{
if(n%i==)
{
if(i!=n)
sum = sum + (n/i)*(opl[n/i]*n/);
LL tmp = n/i;
if(tmp!=i && tmp!=n)
sum = sum + i*(opl[i]*n/);
}
}
printf("%lld\n",sum+n);
}
return ;
}

这样的话,是不行了。

原始相当于

spoj LCMSUM    sigma(lcm(i,n));

也就能转化为(easy)

spoj LCMSUM    sigma(lcm(i,n));

这样的话,我们就能单独的求出euler(a)*a/2;然后用它来筛选g[n]的值。

(x|n的意思代表 n是x的倍数)

我们想到在第一种方法里,我们用sqrt(n)来求它的因子的方法。

同理,逆向一下就好。

这样我们只需要o(N) 的时间对g[]进行筛选。总的预处理时间

3*o(N) = > 3*10^6;

完毕。

需要注意的是,我们没有把gcd() = n的情况包含进去,所以最后要+n。

代码:

 #include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef long long LL; const int maxn = 1e6+;
LL opl[maxn];
LL g[maxn];
void init()
{
for(int i=;i<maxn;i++) opl[i] = i;
//这种方法筛选素数,不用和以前一样要先刷素数,还开num[];
for(int i=;i<maxn;i++)
{
if(opl[i]==i)
opl[i] = i-;
else continue;
for(int j=i+i;j<maxn;j=j+i)
opl[j] = opl[j]/i*(i-);
}
for(int i=;i<maxn;i++){
opl[i] = opl[i]*i/;
g[i] = opl[i];
}
for(long long i=;i<=;i++) //这里的i 不能用int,肯定会超int的
{
for(long long j=i*i,k=i;j<maxn;j=j+i,k++)
if(i!=k) //不重复
g[j] = g[j] + opl[i]+opl[k];
else g[j] = g[j] + opl[i];
}
}
int main()
{
init();
int T;
LL n;
scanf("%d",&T);
while(T--)
{
scanf("%lld",&n);
printf("%lld\n",g[n]*n+n);
}
return ;
}