bzoj 2226 [Spoj 5971] LCMSum

##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.
给出n,计算LCM(1,n)+LCM(2,n)+…+LCM(n,n)的和,LCM(i,n)是i和n的最小公倍数。
##Input
The first line contains T the number of test cases. Each of the next T lines contain an integer n.
第一行输入T表示数据组数,接下来T行每行一个数为n。
##Output
Output T lines, one for each test case, containing the required sum.
输出T行,每行为最小公倍数的和
##Sample Input
3
1
2
5
##Sample Output
1
4
55
##Constraints
1 <= T <= 300000
1 <= n <= 1000000


##Solution
对 于 每 个 n 对于每个n n

A n s = ∑ i = 1 n l c m ( i , n ) Ans=\sum_{i=1}^nlcm(i,n) Ans=i=1nlcm(i,n)

A n s = ∑ i = 1 n n i g c d ( i , n ) Ans=\sum_{i=1}^n\frac{ni}{gcd(i,n)} Ans=i=1ngcd(i,n)ni

A n s = n ∑ i = 1 n i g c d ( i , n ) Ans=n\sum_{i=1}^n\frac{i}{gcd(i,n)} Ans=ni=1ngcd(i,n)i

A n s = n ∑ d ∣ n ∑ i = 1 n i d [ g c d ( i , n d ) = d ] Ans=n\sum_{d|n}\sum_{i=1}^{n}\frac{i}{d}[gcd(i,\frac{n}{d})=d] Ans=ndni=1ndi[gcd(i,dn)=d]

A n s = n ∑ d ∣ n ∑ i = 1 d i [ g c d ( i , d ) = 1 ] Ans=n\sum_{d|n}\sum_{i=1}^{d}i[gcd(i,d)=1] Ans=ndni=1di[gcd(i,d)=1]

设 f ( d ) = ∑ i = 1 d i [ g c d ( i , d ) = 1 ] , 则 A n s = n ∑ d ∣ n f ( d ) 设f(d)=\sum_{i=1}^{d}i[gcd(i,d)=1],则Ans=n\sum_{d|n}f(d) f(d)=i=1di[gcd(i,d)=1],Ans=ndnf(d)

f ( d ) 即 1   d 中 与 d 互 质 的 数 之 和 , f ( d ) = ϕ ( d ) ∗ d 2 f(d)即1~d中与d互质的数之和,f(d)=\frac{\phi(d)*d}{2} f(d)1 ddf(d)=2ϕ(d)d

所 以 , A n s = n ∑ d ∣ n ϕ ( d ) ∗ d 2 所以,Ans=n\sum_{d|n}\frac{\phi(d)*d}{2} Ans=ndn2ϕ(d)d

ϕ ( i ) 可 以 用 线 性 筛 解 决 , 可 以 O ( n l o g 2 n ) 预 处 理 出 所 有 答 案 , 要 记 得 开 l o n g l o n g \phi(i)可以用线性筛解决,可以O(nlog_2^n)预处理出所有答案,要记得开long long ϕ(i)线O(nlog2n)longlong

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

#define N 1000010
#define M 1000000
#define LL long long

LL phi[N],t[N],p[N],tt,n;
LL ans[N];

void pre()
{
	memset(t,0,sizeof(t));
	phi[1]=1;
	for (int i=2;i<=M;i++)
	{
	  if (t[i]==0)
	  {
	  	phi[i]=i-1;
	  	p[++p[0]]=i;
	  }
	  for (int j=1;j<=p[0] && p[j]*i<=M;j++)
	  {
	  	t[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]*phi[p[j]];
	  }
	}
	memset(ans,0,sizeof(ans));
	LL tot;
	for (int i=1;i<=M;i++)
	{
		if (i==1) tot=1;
		  else tot=phi[i]*i/2;
		for (int j=i;j<=M;j+=i)
		  ans[j]+=tot;
	}
}

int main()
{
	pre();
	scanf("%lld",&tt);
	for (int ii=1;ii<=tt;ii++)
	{
		scanf("%lld",&n);
		printf("%lld\n",ans[n]*n);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值