luogu P2257- YY的GCD (莫比乌斯反演)

题意:

求 x 在[1, n]范围内,y 在[1, m]范围内的满足 gcd(x, y) 为质数的x,y对数。

题解:
  • 前面已经计算了gcd(x,y)=k的数量是

    \[f(k) = \sum_{k|d} \mu(\frac{d}{k}) \lfloor\frac{n}{d}\rfloor \lfloor\frac{m}{d}\rfloor \]

  • 所以如果k是质数,我们用p表示,且d = i * p

    \[f(p) = \sum_{i = 1}^{n} \mu(i) \lfloor\frac{n}{ip}\rfloor \lfloor\frac{m}{ip}\rfloor \]

    所以本题答案可以遍历所有质数p,求和f(p)

    \[ans = \sum_{isprime(p)} \sum_{i = 1}^{n} \mu(i) \lfloor\frac{n}{ip}\rfloor \lfloor\frac{m}{ip}\rfloor \]

  • 上面式子肯定很暴力,所以另T=i*p, 将上式转变为

    \[ans = \sum_{T= 1}^{n} \lfloor\frac{n}{T}\rfloor \lfloor\frac{m}{T}\rfloor \sum_{p|T且isprime(p)} \mu(\frac{T}{p}) \]

    后面那一堆我们可以预处理出来。\(sum(T) = \sum_{p|T且isprime(p)} \mu(\frac{T}{p})\)

    \[ans = \sum_{T= 1}^{n} \lfloor\frac{n}{T}\rfloor \lfloor\frac{m}{T}\rfloor sum(T) \]

    O(n)便可以求出来。

//预处理sum(T)
for(int j = 1; j <= cnt; ++ j){
    for(int i = 1; pri[j] * i < N; ++ i){
       sum[i * pri[j]] += mu[i];
    }
}
for(int i = 1; i < N; ++ i)
  	sum[i] = sum[i - 1] + sum[i];
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 1e7 + 5;

int pri[N], cnt;
int vis[N];
int mu[N];
int sum[N];

int read(){
	int q=0;char ch=' ';
	while(ch<'0'||ch>'9')ch=getchar();
	while(ch>='0'&&ch<='9')q=q*10+ch-'0',ch=getchar();
	return q;
}

void prime(){
	mu[1] = 1;
	for(int i = 2; i < N; ++ i){
		if(!vis[i]){
			pri[++ cnt] = i;
			mu[i] = -1;
		}
		for(int j = 1; j <= cnt && pri[j] * i < N; ++ j){
			vis[pri[j] * i] = 1;
			if(i % pri[j] == 0){
				mu[pri[j] * i] = 0;
				break;
			}
			mu[pri[j] * i] = -mu[i];
		}
	}

	for(int j = 1; j <= cnt; ++ j){
		for(int i = 1; pri[j] * i < N; ++ i){
			sum[i * pri[j]] += mu[i];
		}
	}
	for(int i = 1; i < N; ++ i)
		sum[i] = sum[i] + sum[i - 1];
}


int T, n, m;

int main()
{
	prime();
	T = read();
	while(T --){
		n = read(), m = read();
		if(n > m) swap(n, m);
		ll ans = 0;
		for(int i = 1, last = 1; i <= n; i = last + 1){
			last = min(n / (n / i), m / (m / i));
			ans += (ll)(sum[last] - sum[i - 1]) * (n / i) * (m / i);
		}
		printf("%lld\n", ans);
	}
	return 0;
}

posted @ 2020-04-03 17:09  A_sc  阅读(123)  评论(0编辑  收藏  举报