题意:
求 x 在[a, b]范围内,y 在[c, d]范围内的满足 gcd(x, y) = k 的x,y对数。
题解:
- 这道题是在luogu P3455上的拓展。加一个容斥就好了。如果sol(n,m,k)表示x在[1, n]范围内,y在[1, m]范围内的满足gcd(x, y)=k 的x,y对数.
- 那这道题答案就是 ans = sol(b, d, k) - sol(a - 1, d, k) - sol(b, c - 1, k) + sol(a - 1, c - 1, k);
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;
int T, k, a, b, c, d;
int pri[N], cnt;
int mu[N];
int vis[N];
int sum[N];
void prime(){
mu[1] = 1;
sum[1] = 1;
for(int i = 2; i <= 4e5; ++ i){
if(!vis[i]){
pri[++ cnt] = i;
mu[i] = -1;
}
for(int j = 1; j <= cnt && pri[j] * i <= 4e5; ++ j){
vis[pri[j] * i] = 1;
if(i % pri[j] == 0){
mu[pri[j] * i] = 0;
break;
}
mu[pri[j] * i] = -mu[i];
}
sum[i] = sum[i - 1] + mu[i];
}
}
ll sol(ll n, ll m, ll k){
n /= k, m /= k;
ll res = 0;
if(n > m) swap(n, m);
for(int i = 1, last = 1; i <= n; i = last + 1){
last = min(n / (n / i), m / (m / i));
res += (ll)(sum[last] - sum[i - 1]) * (n / i) * (m / i);
}
return res;
}
int main()
{
prime();
scanf("%d",&T);
for(int Case = 1; Case <= T; ++ Case){
scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);
ll ans = sol(b, d, k) - sol(a - 1, d, k) - sol(b, c - 1, k) + sol(a - 1, c - 1, k);
printf("%lld\n", ans);
}
return 0;
}