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).
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.
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
Source
The 5th Guangting Cup Central China Invitational Programming Contest
题解
- 若要一个数x与m,n均互质,x则不能含义m,n的素因子。因为k很大,暴力求会超时。
- 由容斥原理我们知道,只要x里没有m,n的素因子就是互质,那么1-n内的,对m,n互质的数的个数我们就可以认为是n-cal(n),(cal()函数为计算1-n中与m,n不互质数的个数)
- 对于m,n的素因子,我们不能通过m*n求,而时分别求m,n,然后排序得到去除重复的素因子数组fac[]。
- 二分搜索,那么对于第k个互质数,我们只要搜索n-cal(n)=k时,说明,1-n区间有k个互质数,但n不一定是第k个互质数,这时候要对n递减,只要n不满足这个条件我们就可以返回n+1.
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
const LL INF=1e18+5;
int fac[1005];//数组大小视具体情况而定
int cnt;
void getFactor(LL n)
{//求n的所有质因素
LL m=sqrt(n+0.5);
for(LL i=2;i<=m&&n;i++){
if(n%i==0){
fac[cnt++]=i;
while(n&&n%i==0) n/=i;
}
}
if(n>1) fac[cnt++]=n;
}
LL cal(LL n)
{//容斥
LL res=0;
for(LL i=1;i<(1LL<<cnt);i++){
LL mult=1,ones=0;
for(int j=0;j<cnt;j++){
if(i&(1<<j)){
ones++;
mult*=fac[j];
}
}
if(ones&1) res+=n/mult;
else res-=n/mult;
}
return res;
}
LL bin_serach(LL k)
{//二分搜索
LL l=0,r=INF,mid;
while(l<r){
mid=(l+r)>>1;
LL d=mid-cal(mid);
if(d>=k) r=mid;
else l=mid+1;
}
return r;
}
int main()
{
int T;
scanf("%d",&T);
for(int cas=1;cas<=T;++cas){
LL n,m,k;
cnt=0;
scanf("%lld%lld%lld",&n,&m,&k);
getFactor(n);
getFactor(m);
sort(fac,fac+cnt);
cnt=unique(fac,fac+cnt)-fac;//去重
printf("Case %d: %lld\n",cas,bin_serach(k));
}
return 0;
}注:这个是二分搜索的特殊形式,实在不懂就用下面这个。
二分搜索详解 戳这<<
LL bin_serach(LL k)
{//二分搜索
LL l=0,r=INF,mid;
while(l<=r){
mid=(l+r)>>1;
LL d=mid-cal(mid);
if(d>k) r=mid-1;
else if(d<k) l=mid+1;
else{
while(d==k){
mid--;
d=mid-cal(mid);
}
return mid+1;
}
}
return r;
}版权声明:本文为deaidai原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。