hdu1695 GCD 容斥原理

时间:2023-03-09 18:28:53
hdu1695 GCD 容斥原理

Given 5 integers: a, b, c, d, k, you're to find x in a...b, y in c...d that GCD(x, y) = k. GCD(x, y) means the greatest common divisor of x and y. Since the number of choices may be very large, you're only required to output the total number of different number pairs.
Please notice that, (x=5, y=7) and (x=7, y=5) are considered to be the same.

Yoiu can assume that a = c = 1 in all test cases.

 

容斥原理的裸题

 #include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
typedef long long ll; const int maxn=2e5+; int pnum[maxn][],num[maxn]; void init(){
memset(pnum,,sizeof(pnum));
memset(num,,sizeof(num));
for(int i=;i<=;++i){
if(!num[i]){
pnum[i][++num[i]]=i;
for(int j=;i*j<=;++j){
pnum[i*j][++num[i*j]]=i;
}
}
}
} int main(){
init();
int T;
scanf("%d",&T);
for(int q=;q<=T;++q){
int a,b,c,d,k;
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
if(!k){
printf("Case %d: 0\n",q);
continue;
}
a=b/k;b=d/k;
if(a>b){c=a;a=b;b=c;}
ll ans=;
if(a>=)ans+=b;
for(int p=;p<=a;++p){
ll res=;
for(int i=;i<(<<num[p]);++i){
int bit=;
ll mul=;
for(int j=;j<=num[p];++j){
if(i&(<<(j-))){
++bit;
mul*=pnum[p][j];
}
}
if(bit%)res+=(b/mul-(p-)/mul);
else res-=(b/mul-(p-)/mul);
}
ans+=b-(p-)-res;
}
printf("Case %d: %lld\n",q,ans);
}
return ;
}