题意
对于给出的 n 个询问,每次求有多少个数对 (x,y) ,满足 a ≤ x ≤ b , c ≤ y ≤ d ,且 gcd(x,y) = k , gcd(x,y) 函数为 x 和 y 的最大公约数。
n, a, b, c, d, k都是1e5
思路
- 用容斥原理处理a ≤ x ≤ b , c ≤ y ≤ d的情况,即 bd - ad - bc + ac
- 用之前普通做法的复杂度为1e5,加上1e5次询问,总的复杂度是 n2 级别的,肯定要T
- 因为F(e)的值与n/e和m/e有关,所以值的种类是 O(n√)
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 4;
const int inf = 0x3f3f3f3f;
bool check[maxn+10];
int prime[maxn+10];
int mu[maxn+10];
int sum[maxn+10];
void Moblus(){
memset(check,false,sizeof(check));
mu[1] = sum[1] = 1;
int tot = 0;
for(int i = 2; i <= maxn; i++){
if(!check[i]){
prime[tot++] = i;
mu[i] = -1;
}
for(int j = 0; j < tot; j++){
if(i * prime[j] > maxn) break;
check[i * prime[j]] = true;
if( i % prime[j] == 0){
mu[i * prime[j]] = 0;
break;
}
else{
mu[i * prime[j]] = -mu[i];
}
}
sum[i] = sum[i - 1] + mu[i];
}
}
int a, b, c, d, k;
ll get_f1(int n, int m) {
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);
}
return ans;
}
int main(){
int T;
scanf("%d", &T);
Moblus();
while(T--){
scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);
a = (a - 1) / k;
b /= k;
c = (c - 1) / k;
d /= k;
ll f11 = get_f1(b, d);
ll f12 = get_f1(a, c);
ll f13 = get_f1(a, d);
ll f14 = get_f1(b, c);
ll f1 = f11 + f12 - f13 - f14;
printf("%lld\n",f1);
}
return 0;
}