HDU4135容斥原理
Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8481 Accepted Submission(s): 3374
Problem Description
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.
Input
The first line on input contains T (0 < T <= 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 1015) and (1 <=N <= 109).
Output
For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.
Sample Input
2
1 10 2
3 15 5
Sample Output
Case #1: 5
Case #2: 10
Hint
In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.
Source
The Third Lebanese Collegiate Programming Contest
题解:容斥原理
求[a,b]中与k互质的个数,即求[1,b]与k互质的个数-[1,a-1]与k互质的个数。
求区间[1,n]与k互质的个数,我们先求[1,n]与k不是互质的数的个数。
我们先把k的质因数全部求出来,用数组p[]来保存,质因数个数即为num
接下来没有质因数的组合情况,这里用二进制状态压缩来枚举。
举个栗子?求[1,20]中与6不互质的数的个数
结果显而易见sum = 20 / 2 + 20 / 3 - 20 / 6;
我们已经求得p[0]= 2,p[1] = 3; num = 2;
所以共有1<<num中组合情况,枚举i from 1 to 1<<num
当i = 1,01,选择质因数2, sum += 20/2=10;
当i = 2,10,选择质因数3, sum += 20/3=6;
当i = 3,11,选择质因数2和3, sum -= 20/6 =3;
我们发现奇数加,偶数减,所以用一个bit来记录
具体代码如下
#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
typedef long long LL;
int const N = 1e5;
LL a,b,n,cnt,T,p[N];
LL solve(LL r,int n){
LL sum = 0,num = 0;
for(int i=2;i*i<=n;i++){
if(n%i == 0){
p[num++] = i;
while(n%i == 0) n /= i;
}
}
if(n>1) p[num++] = n;
for(LL msk=1;msk<(1<<num);msk++){ //枚举每次选择哪几个质因数
LL bit = 0,mult = 1;
for(int i=0;i<num;i++){
if(msk&(1<<i)){ //如果选中了这个质因数
bit++;
mult *= p[i];
}
}
LL cur = r / mult;
if(bit&1) sum += cur;
else sum -= cur;
}
return r - sum;
}
int main()
{
cin>>T;
while(T--){
cin>>a>>b>>n;
printf("Case #%d: ",++cnt);
cout<<solve(b,n)- solve(a-1,n)<<endl;
}
return 0;
}

浙公网安备 33010602011771号