Luogu P2257 YY的GCD

题目描述

https://www.luogu.com.cn/problem/P2257

简要题意:求 $\sum_{p}\sum_{i=1}^n\sum_{j=1}^m[(i,j)=p]$

$T=10^4,n,m\le 10^7$

Solution

我们令 $f(T)=\sum_{p|T}\mu(\frac{T}{p})$,这个东西可以 $O(n)$ 预处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cstdio>
#define maxn 10000010
#define ll long long
using namespace std;

int n, m, k;

int pri[maxn], cnt, mu[maxn], f[maxn]; bool isp[maxn];
void init_isp(int n) {
mu[1] = 1;
for (int i = 2; i <= n; ++i) {
if (!isp[i]) pri[++cnt] = i, mu[i] = -1;
for (int j = 1; j <= cnt && i * pri[j] <= n; ++j) {
isp[i * pri[j]] = 1;
if (i % pri[j] == 0) break;
mu[i * pri[j]] = -mu[i];
}
}
for (int i = 1; i <= cnt; ++i)
for (int j = pri[i], k = 1; j <= n; j += pri[i], ++k) f[j] += mu[k];
for (int i = 1; i <= n; ++i) f[i] += f[i - 1];
}

void work() {
cin >> n >> m; if (n > m) swap(n, m); ll ans = 0;
for (int l = 1, r; l <= n; l = r + 1) {
r = min(n / (n / l), m / (m / l));
ans += (ll) (f[r] - f[l - 1]) * (n / l) * (m / l);
}
cout << ans << "\n";
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

int T; cin >> T; init_isp(10000000);
while (T--) work();
return 0;
}