YY的GCD
Posted fly-in-milkyway
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了YY的GCD相关的知识,希望对你有一定的参考价值。
Description
给出 (T) 组 (n, m),求 (1 leq i leq n, 1 leq j leq m) 且 (gcd(i, j)) 为质数的 ((i, j)) 有多少对。
Solution
假设 (n<m)
[sumlimits_{isprime(p)}sumlimits_{i=1}^{n}sumlimits_{j=1}^{m}[gcd(i,j)=p]\sumlimits_{isprime(p)}sumlimits_{i=1}^{lfloorfrac{n}{p} floor}sumlimits_{j=1}^{lfloorfrac{m}{p} floor}[gcd(i,j)=1]\sumlimits_{isprime(p)}sumlimits_{i=1}^{lfloorfrac{n}{p} floor}sumlimits_{j=1}^{lfloorfrac{m}{p} floor}sumlimits_{d|gcd(i,j)}mu(d)\sumlimits_{isprime(p)}sumlimits_{i=1}^{lfloorfrac{n}{p} floor}sumlimits_{j=1}^{lfloorfrac{m}{p} floor}sumlimits_{d|iwedge d|j}mu(d)\sumlimits_{isprime(p)}sumlimits_{d=1}^{lfloorfrac{n}{p} floor}mu(d){leftlfloorfrac{n}{pd} ight floor}{leftlfloorfrac{m}{pd} ight floor}]
设 (k=pd)
[sumlimits_{k=1}^{n}sumlimits_{isprime(p)wedge p|k}mu(frac{k}{p}){leftlfloorfrac{n}{k} ight floor}{leftlfloorfrac{m}{k} ight floor}\sumlimits_{k=1}^{n}f(k){leftlfloorfrac{n}{k} ight floor}{leftlfloorfrac{m}{k} ight floor}]
线性筛出 (f) 数组,然后整除分块,复杂度 (O(n+T(sqrt n+sqrt m)))。
Code
#include <cstdio>
const int N = 10000005;
int n, m, T, tot, np[N], p[N], mu[N], sum[N];
int min(int x, int y) {
return x < y ? x : y;
}
void getmu(int n) {
np[1] = mu[1] = 1;
for (int i = 2; i <= n; ++i) {
if (!np[i]) p[++tot] = i, mu[i] = -1;
for (int j = 1; j <= tot && p[j] * i <= n; ++j) {
np[p[j]*i] = 1;
if (i % p[j] == 0) {
mu[p[j]*i] = 0;
break;
} mu[p[j]*i] = -mu[i];
}
}
}
void prev(int n) {
for (int i = 1; i <= tot; ++i)
for (int j = p[i]; j <= n; j += p[i])
sum[j] += mu[j/p[i]];
for (int i = 2; i <= n; ++i) sum[i] += sum[i-1];
}
int main() {
scanf("%d", &T), getmu(1e7), prev(1e7);
while (T--) {
scanf("%d%d", &n, &m);
if (n > m) n ^= m, m ^= n, n ^= m;
long long ans = 0;
for (int l = 1, r; l <= n; l = r + 1) {
r = min(n / (n / l), m / (m / l));
ans += 1LL * (sum[r] - sum[l-1]) * (n / l) * (m / l);
}
printf("%lld
", ans);
}
return 0;
}
以上是关于YY的GCD的主要内容,如果未能解决你的问题,请参考以下文章