Description
对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数。
Input
第一行一个整数n,接下来n行每行五个整数,分别表示a、b、c、d、k
Output
共n行,每行一个整数表示满足要求的数对(x,y)的个
Sample Input
2
2 5 1 5 1
1 5 1 5 2
Sample Output
14
3
HINT
100%的数据满足:1≤n≤50000,1≤a≤b≤50000,1≤c≤d≤50000,1≤k≤50000
题解
我们现将问题用容斥原理分解。
求a≤x≤b,c≤y≤d中gcd(x,y)=k的x,y对数,不如求1≤x≤b,1≤y≤d中的,再减去1≤x≤b,1≤y≤c-1,1≤x≤a-1,1≤y≤d,加上1≤x≤a-1,1≤y≤c-1就得到答案了。
然后求就用莫比乌斯反演就可以了。
记g(k)是gcd(x,y)=k的答案。
我们发现,单独求g(k)很难,但是我们可以求出gcd(x,y)是k的倍数的(x,y)对数。记f(k)是k|gcd(x,y)的(x,y)对数。
求出f后反推回g就行了。(具体直接套公式求)
最后这样单组数据能过但多组过不了,用分块优化就行了。
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#define N 50010
using namespace std;
bool vis[N + 10];
int n, cnt, prime[N + 10], miu[N + 10], sum[N + 10];
int a, b, c, d, k;
typedef long long LL;
void Get_miu(){//线性求miu
miu[1] = 1; vis[1] = true;
for(int i = 1; i <= N; i++){
if(!vis[i]){
prime[++cnt] = i;
miu[i] = -1;
}
for(int j = 1; j <= cnt && i * prime[j] <= N; j++){
vis[i * prime[j]] = true;
if(i % prime[j] == 0){
miu[i * prime[j]] = 0;
break;
}
else miu[i * prime[j]] = -miu[i];
}
}
sum[0] = 0;
for(int i = 1; i <= N; i++) sum[i] = sum[i-1] + miu[i];//处理前缀和,为分块优化所用
}
LL Getans(int x, int y){
x /= k; y /= k;
if(x > y) swap(x, y);
LL res = 0; int last;
for(int i = 1; i <= x; i = last+1){
last = min(x/(x/i), y/(y/i));
res += (LL)(x/i)*(y/i)*(sum[last]-sum[i-1]);//分块优化
}
return res;
}
int main(){
scanf("%d", &n);
Get_miu();
while(n --){
scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);
LL ans1 = Getans(b, d), ans2 = Getans(a-1, d);
LL ans3 = Getans(b, c-1), ans4 = Getans(a-1, c-1);
printf("%lld\n", ans1 - ans2 - ans3 + ans4);//容斥出答案
}
return 0;
}
长的是黑夜,短的是人生。