http://acm.hdu.edu.cn/showproblem.php?pid=3388
容斥定理,题意:给两个数n,m,问第k个跟他们互质的数是啥,刚看到这一题的时候,果断弄出n,m的lcm,但是超时了,后来左改右改连滚带爬过了
Coprime
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 760 Accepted Submission(s): 201
Problem Description
Please write a program to calculate the k-th positive integer that is coprime with m and n simultaneously. A is coprime with B when their greatest common divisor is 1.
Input
The first line contains one integer T representing the number of test cases.
For each case, there's one line containing three integers m, n and k (0 < m, n, k <= 10^9).
For each case, there's one line containing three integers m, n and k (0 < m, n, k <= 10^9).
Output
For each test case, in one line print the case number and the k-th positive integer that is coprime with m and n.
Please follow the format of the sample output.
Please follow the format of the sample output.
Sample Input
3 6 9 1 6 9 2 6 9 3
Sample Output
Case 1: 1 Case 2: 5 Case 3: 7
Author
xay@whu
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<__int64> fac;
void get_fac(__int64 n,__int64 m){
for(__int64 i=2;i*i<=n;i++)
if(n%i==0){
fac.push_back(i);
while(n%i==0)n/=i;
}
if(n>1)
fac.push_back(n);
for(__int64 i=2;i*i<=m;i++)
if(m%i==0){
fac.push_back(i);
while(m%i==0)m/=i;
}
if(m>1)fac.push_back(m);
sort(fac.begin(),fac.end());
fac.erase(unique(fac.begin(),fac.end()),fac.end());
}
__int64 gcd(__int64 x,__int64 y){
return y?gcd(y,x%y):x;
}
__int64 fun(__int64 x){
__int64 sum=0;
__int64 cnt=fac.size();
for(int num=1;num<(1<<cnt);num++){//cnt个集合,容斥定理中就有2的cnt次方-1项,num是二进制压缩//3为11,代表A1交A2
__int64 mult=1,ones=0;
for(int i=0;i<cnt;i++){//i表示第几个集合,例如i=2,表示为100,表示为第三个集合
if(num&(1<<i)){//当i为0的时候,判断第一个集合是否进行交集操作
ones++;//当ones为偶数的时候,那么就是减,当noes为奇数的时候为加
mult*=fac[i];
}
}
if(ones%2) sum+=x/mult;
else sum-=x/mult;
}
return x-sum;
}
//这里的fac是指一个数n的素因子,a表示1~a大小的集合,所求是1~a内与n互质的数的个数
__int64 get_ans(__int64 low,__int64 high,__int64 n,__int64 m,__int64 k){//注意这里二分的次序,如果次序颠倒了,会有意想不到的事情,一开始没注意,超时无数
__int64 mid=(low+high)/2;
if (fun(mid)>k) return get_ans(low,mid-1,n,m,k);
else if(fun(mid)<k)
return get_ans(mid+1,high,n,m,k);
else {
for(;;mid--){
if(gcd(mid,n)==1&&gcd(mid,m)==1) {
return mid;
}
}
}
}
int main()
{
__int64 m,n,k,t;
scanf("%I64d",&t);
__int64 maxn=(__int64)1<<62;
for(int Case=1;Case<=t;Case++){
scanf("%I64d%I64d%I64d",&m,&n,&k);
fac.clear();
get_fac(n,m);
__int64 ans=get_ans(1,maxn,n,m,k);
printf("Case %d: %I64d\n",Case,ans);
}
return 0;
}