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.
容斥原理
1 #include<stdio.h>
2 #include<string.h>
3 #include<algorithm>
4 #include<math.h>
5 using namespace std;
6 typedef long long ll;
7
8 int pnum[500];
9
10 int main(){
11 int T;
12 scanf("%d",&T);
13 for(int q=1;q<=T;++q){
14 ll a,b;
15 int n;
16 scanf("%lld%lld%d",&a,&b,&n);
17 a--;
18 ll ans=0;
19 int cnt=0;
20 for(int i=2;i*(ll)i<=n;++i){
21 if(!(n%i)){
22 pnum[++cnt]=i;
23 while(!(n%i))n/=i;
24 }
25 }
26 if(n>1)pnum[++cnt]=n;
27 for(int i=1;i<(1<<cnt);++i){
28 int bit=0;
29 int mul=1;
30 for(int j=1;j<=cnt;++j){
31 if(i&(1<<(j-1))){
32 bit++;
33 mul*=pnum[j];
34 }
35 }
36 if(bit%2)ans+=b/mul-a/mul;
37 else ans-=b/mul-a/mul;
38 }
39 printf("Case #%d: %lld
",q,b-a-ans);
40 }
41 return 0;
42 }