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.
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 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.
3
6 9 1
6 9 2
6 9 3
Case 1: 1
Case 2: 5
Case 3: 7
xay@whu
The 5th Guangting Cup Central China Invitational Programming Contest
思路:这题我是用的二分+容斥,令d为一个很大的数字,那么第k个与m和n同时互素的数一定在1~d里面,先判断1~h(h=(1+d)/2)内与m和
n同时互素的有多少个(用容斥定理进行判断),如果大于k就从(h~l)进行判断,如果小于k,就从1~h进行判断;直到等于k,这时候判断h--,直到1~h内与m和n互素的个数为k-1这时候返回h+1;
代码如下:
#include
#include
using namespace std;
#define LL long long
LL prime[100000], p[100000], vis[50000] = {1, 1}, cnt = 0, l = 0;
LL Repulsion(LL m)
{
LL res = m;
for(int i = 1; i < (1 << l); i++){
LL s = 1, f = 0;
for(int j = 0; j < l; j++)
if(i & (1 << j))
{
s *= p[j];
f++;
}
if(f % 2 == 1)
res -= m / s;
else
res += m / s;
}
return res;
}
LL BinarySearch(LL low, LL high, LL k)
{
while(low <= high){
LL mid = (low + high) >> 1;
LL m = Repulsion(mid) , M = Repulsion(mid - 1);
if(m == k)
{
while(Repulsion(mid-1) == k) mid--;
return mid;
}
if(m > k)
high = mid - 1;
else
low = mid + 1;
}
}
int main()
{
ios::sync_with_stdio(false);
for(int i = 2; i <= 250; i++)
if(!vis[i])
for(int j = i * i; j <= 50000; j += i)
vis[j] = 1;
for(int i = 2; i <= 50000; i++)
if(!vis[i])
prime[cnt++] = i;
int t;
cin >> t;
for(int cases = 1; cases <= t; cases++){
int n , m , k;
l = 0;
cin >> n >> m >> k;
int x = max(sqrt(n + 0.5), sqrt(m + 0.5));
for(int i = 0; prime[i] <= x && i < cnt; i++)
if(n % prime[i] == 0 || m % prime[i] == 0){
p[l++] = prime[i];
while(n % prime[i] == 0) n /= prime[i];
while(m % prime[i] == 0) m /= prime[i];
}
if(n > 1) p[l++] = n;
if(m > 1 && m != n) p[l++] = m;
cout<<"Case "<