Coprime

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

 

思路:这题我是用的二分+容斥,令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<iostream>
#include<algorithm>
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 "<<cases<<": "<<BinarySearch(1, 1e18, k)<<endl;
    }
    return 0;
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值