洛谷1390 公约数的和

题 意 : 题意: :

求 ∑ i = 1 n ∑ j = i + 1 n gcd ⁡ ( i , j ) 求\sum_{i=1}^{n} \sum_{j=i+1}^{n}\gcd(i, j) i=1nj=i+1ngcd(i,j)

题 解 : 题解: :

原 式 = ∑ i = 1 n ∑ j = i + 1 n gcd ⁡ ( i , j ) = ∑ d = 1 n d ⋅ ∑ i = 1 n ∑ j = i + 1 n [ g c d ( i , j ) = d ] = ∑ d = 1 n d ⋅ ∑ i = 1 n / d ∑ j = i + 1 n / d [ g c d ( i , j ) = 1 ] = ∑ d = 1 n d ⋅ ∑ j = 1 n / d ϕ ( j ) \begin{aligned} \qquad\qquad\qquad 原式 &= \sum_{i=1}^{n} \sum_{j=i+1}^{n}\gcd(i, j)\\ &= \sum_{d=1}^{n} d \cdot \sum_{i=1}^{n} \sum_{j=i+1}^{n}[gcd(i, j)=d]\\ &= \sum_{d=1}^{n} d \cdot \sum_{i=1}^{n/d} \sum_{j=i+1}^{n/d}[gcd(i, j)=1]\\ &= \sum_{d=1}^{n} d \cdot \sum_{j=1}^{n/d} \phi(j)\\ \end{aligned} =i=1nj=i+1ngcd(i,j)=d=1ndi=1nj=i+1n[gcd(i,j)=d]=d=1ndi=1n/dj=i+1n/d[gcd(i,j)=1]=d=1ndj=1n/dϕ(j)

因 此 预 处 理 出 欧 拉 函 数 的 前 缀 和 , 然 后 枚 举 d 即 可 因此预处理出欧拉函数的前缀和,然后枚举d即可 d

#include 
using namespace std;

typedef long long LL;

const int N = 2000020;
int n, phi[N], p[N];
LL sum[N];
int tot;
bool used[N];

//预处理出素数 欧拉函数 欧拉函数前缀和
void init(LL n) {
	phi[1] = 0;
	for (int i = 2; i <= n; i++) {
		if (!used[i]) {
			phi[i] = i - 1;
			p[++tot] = i;
		}
		for (int j = 1; p[j] * i <= n; j++) {
			used[p[j] * i] = true;
			if (i % p[j] == 0) {
				phi[i * p[j]] = phi[i] * p[j];
				break;
			}
			phi[i * p[j]] = phi[i] * (p[j] - 1);
		}
	}
	for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + phi[i];
}

LL cal(LL x) {
	LL res = 0;
	for (int i = 1; i <= x; i++) {
		int t = x / i;
		res += 1LL * sum[t] * i;
	}
	return res;
}


int main() {
	int x;
	cin >> x;
	init(x);
	cout << cal(x) << endl;
	return 0;
}

你可能感兴趣的:(数学)