跳到正文

个人记录

一道题

rsy_约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年2月26日
篇幅
约 5 分钟

版本

  1. v1当前

有 tt 个 nn,对于每一个 nn 求 ∑x∣nn∑y=1x[y×(gcd⁡(x,y)=1)]\sum\limits_{x|n}^{n}\sum\limits_{y = 1}^{x}[y\times(\gcd(x,y)=1)]。

其中 t≤103,n≤109t\le10^3,n\le10^9。

结论 ∑x∣nn∑y=1x[y×(gcd⁡(x,y)=1)]=∑x∣nnφ(n)2\sum\limits_{x|n}^{n}\sum\limits_{y = 1}^{x}[y\times(\gcd(x,y)=1)] =\sum\limits_{x|n}\frac{n\varphi(n)}{2}。

证明:对于 gcd⁡(a,n)=1\gcd(a,n)=1 必有 gcd⁡(n−a,n)\gcd(n-a,n) 所以是成对出现的。

我们知道成对出现的两个数的和 a+n−a=na+n-a=n 所以任何的对和都是 nn。

所以可以得到 ∑x∣nn∑y=1x[y×(gcd⁡(x,y)=1)]\sum\limits_{x|n}^{n}\sum\limits_{y = 1}^{x}[y\times(\gcd(x,y)=1)] 为 xφ(x)2\frac{x\varphi(x)}{2} 然后就可以直接求了。

注:建议不要用筛子(像我一样),可以直接枚举,筛子莫名其妙变慢了。

C++
#include<bits/stdc++.h>
#pragma GCC optimize(1,2,3,"Ofast")
#define rep(i,j,k) for(int i=(j);i<=(k);++i)
#define per(i,j,k) for(int i=(j);i>=(k);--i)

using namespace std;

const int MAXSIZE = 1 << 20;
char buf[MAXSIZE], *p1, *p2;
#define gc()                                                               \
  (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin), p1 == p2) \
       ? EOF                                                               \
       : *p1++)

int rd() {
  int x = 0, f = 1;
  char c = gc();
  while (!isdigit(c)) {
    if (c == '-') f = -1;
    c = gc();
  }
  while (isdigit(c)) x = x * 10 + (c ^ 48), c = gc();
  return x * f;
}

namespace rsy{
	const int N = 4e5 + 10;
	typedef long long ll;
	typedef unsigned long long ull;
	typedef pair<int, int> pii;

	int qmi(int a,int b){
		int res=1;
		while(b){
			if(b&1)res*=a;
			a*=a,b>>=1;
		}return res;
	}
	int t,n,primes[N],cnt,idx;
	pii fj[100];
	bool st[N];
	void fjj(int x){
		for(int i=1;i<=cnt;i++){
			int s=0;
			if(!st[i])break;
			while(x%primes[i]==0)x/=primes[i],s++;
			if(!s)break;
			fj[++idx]={primes[i],s};
		}
		if(x>1)fj[++idx]={x,1};
	}
	void init(int x){
		for(int i=2;i<=x;++i){
			if(!st[i])primes[++cnt]=i;
			for(int j=1;primes[j]<=x/i;j++){
				st[primes[j]*i]=1;
				if(i%primes[j]==0)break;
			}
		}
	}
	int phi(int x){
		int res=x,t=ceil(sqrt(x));
		for(int i=1;;i++){
			if(primes[i]>t)break;
			if(x%primes[i]!=0)continue;
			while(x%primes[i]==0)x/=primes[i];
			res=res/primes[i]*(primes[i]-1);
		}
		if(x>1)res=res/x*(x-1);
		return res;
	}

	signed main()
	{
		init(35000);
		t=rd();
		while(t--){
			ll res=0;idx=0;
			n=rd();
			if(n==1){printf("1\n");continue;}
			for(int i=1;i<=n/i;i++)
				if(n%i==0){
					res+=(1ll*i*phi(i)+1ll)>>1ll;
					if(i!=n/i)res+=(1ll*(n/i)*phi(n/i)+1ll)>>1ll;
				}
			printf("%lld\n",res);
		}
		return 0;
	}
}

signed main()
{

	return rsy::main();
}

感谢 six_one 对于 LaTeX 错误的贡献!

原文