hdu4135 Co-prime 容斥原理

时间:2023-03-10 01:03:03
hdu4135 Co-prime 容斥原理

Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.

容斥原理

 #include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
typedef long long ll; int pnum[]; int main(){
int T;
scanf("%d",&T);
for(int q=;q<=T;++q){
ll a,b;
int n;
scanf("%lld%lld%d",&a,&b,&n);
a--;
ll ans=;
int cnt=;
for(int i=;i*(ll)i<=n;++i){
if(!(n%i)){
pnum[++cnt]=i;
while(!(n%i))n/=i;
}
}
if(n>)pnum[++cnt]=n;
for(int i=;i<(<<cnt);++i){
int bit=;
int mul=;
for(int j=;j<=cnt;++j){
if(i&(<<(j-))){
bit++;
mul*=pnum[j];
}
}
if(bit%)ans+=b/mul-a/mul;
else ans-=b/mul-a/mul;
}
printf("Case #%d: %lld\n",q,b-a-ans);
}
return ;
}