洛谷 - YY的GCD
莫比乌斯反演
P2257 YY的GCD - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题意
有 \(T\;(1<=T<=10^4)\) 组数据,每组给定两个正整数 \(n,m\;(1<=n,m<=10^7)\)
求 \(1<=i<=n,\;1<=j<=m\) 的 \((i,j)\) 中 \(\gcd(i,j)\) 为质数的有多少对
思路
\[\begin{aligned}
& ans=\sum\limits_{p\in primes}\sum\limits_{i=1}^n\sum\limits_{j=1}^m[\gcd(i,j)==p]\\
&\;\;\;\;\;\;\;=\sum\limits_{p\in primes}\sum\limits_{i=1}^{\lfloor\frac np\rfloor }\sum\limits_{j=1}^{\lfloor\frac mp\rfloor }[\gcd(i,j)==1]\\
&\;\;\;\;\;\;\;=\sum\limits_{p\in primes}\sum\limits_{d=1}^n\mu(d)*\lfloor\frac n{d*p}\rfloor*\lfloor\frac m{d*p}\rfloor\\
&令\; T=d*p\\
&\;\;\;\;\;\;\;=\sum\limits_{T=1}^n\sum\limits_{p\mid T}\mu(\frac Tp)*\lfloor \frac nT\rfloor*\lfloor \frac mT\rfloor\\
&令\;h(T)=\sum\limits_{p\mid T}\mu(\frac Tp)\\
&枚举\;p,\;根据调和级数可在 O(nlnn) 预处理出h(T)
\end{aligned}
\]
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
using namespace std;
#define endl "\n"
typedef long long ll;
typedef pair<int, int> PII;
const int N = 1e7 + 10;
int n;
int pr[N / 5], p[N], pe[N], cnt;
int mu[N], h[N];
ll s[N];
void get_primes(int n)
{
p[1] = 1;
for (int i = 2; i <= n; i++)
{
if (!p[i])
{
p[i] = i;
pr[++cnt] = i;
pe[i] = i;
}
for (int j = 1; j <= cnt && pr[j] <= n / i; j++)
{
p[i * pr[j]] = pr[j];
if (p[i] == pr[j])
{
pe[i * pr[j]] = pe[i] * pr[j];
break;
}
pe[i * pr[j]] = pr[j];
}
}
}
void presolve(int n)
{
mu[1] = s[1] = 1;
for (int i = 2; i <= n; i++)
{
if (i == pe[i])
mu[i] = (i == p[i] ? -1 : 0);
else
mu[i] = mu[i / pe[i]] * mu[pe[i]];
}
for (int i = 1; i <= cnt; i++)
{
for (int j = pr[i]; j <= n; j += pr[i])
h[j] += mu[j / pr[i]];
}
for (int i = 1; i <= n; i++)
s[i] = s[i-1] + h[i];
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
get_primes(N - 10);
presolve(N - 10);
int T;
cin >> T;
while(T--)
{
int n, m;
cin >> n >> m;
if (n > m) swap(n, m);
ll ans = 0;
for (int l = 1; l <= n; l++)
{
int r = min(n / (n / l), m / (m / l));
ans += (s[r] - s[l-1]) * (n / l) * (m / l);
l = r;
}
cout << ans << endl;
}
return 0;
}