bzoj 2226 [Spoj 5971] LCMSum

本文介绍了一种计算从1到n的所有整数与n的最小公倍数之和的方法。通过数学推导,将问题转化为求解特定函数f(d)的值,并利用线性筛法高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

##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对于每个nn

Ans=∑i=1nlcm(i,n)Ans=\sum_{i=1}^nlcm(i,n)Ans=i=1nlcm(i,n)

Ans=∑i=1nnigcd(i,n)Ans=\sum_{i=1}^n\frac{ni}{gcd(i,n)}Ans=i=1ngcd(i,n)ni

Ans=n∑i=1nigcd(i,n)Ans=n\sum_{i=1}^n\frac{i}{gcd(i,n)}Ans=ni=1ngcd(i,n)i

Ans=n∑d∣n∑i=1nid[gcd(i,nd)=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]

Ans=n∑d∣n∑i=1di[gcd(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=1di[gcd(i,d)=1],则Ans=n∑d∣nf(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)∗d2f(d)即1~d中与d互质的数之和,f(d)=\frac{\phi(d)*d}{2}f(d)1 ddf(d)=2ϕ(d)d

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

ϕ(i)可以用线性筛解决,可以O(nlog2n)预处理出所有答案,要记得开longlong\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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值