Poj2773容斥原理

题意:求第k个与m互质的数。

容斥原理求出[1,L]与m互质的数,然后二分k即可。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<string>
#include<queue>
#include<stack>
#include<list>
#include<stdlib.h>
#include<algorithm>
#include<vector>
#include<map>
#include<cstring>
#include<set>
using namespace std;
typedef long long LL;
const LL INF = (1LL) << 62;
vector<LL>  q;
LL ans;
void ask(LL x, LL pre, LL flag, LL key)
{
    if (x == q.size()) {
        if (flag == 0) ans -= key / pre;
        else ans += key / pre;
        return;
    }
    ask(x + 1, pre, flag, key);
    ask(x + 1, pre*q[x], flag ^ 1, key);
}


LL erfen(LL l, LL r, LL key)
{
    LL cnt = -1;
    while (l <= r) {
        LL mid = (l + r) >> 1;
        ans = 0;
        ask(0, 1, 1, mid);
        if (ans == key) {
            cnt = mid;
        }
        if (key <= ans) r = mid - 1;
        else l = mid + 1;
    }
    return cnt;
}

int main()
{
    LL m, k;
    while (scanf("%I64d%I64d", &m, &k) != EOF) {
        q.clear();
        LL t = m;
        for (LL i = 2; i*i <= t; i++) {
            if (t%i) continue;
            while (t%i==0) t /= i;
            q.push_back(i);
        }
        if (t > 1) q.push_back(t);
        LL cc = erfen(1, INF, k);
        cout << cc << endl;
    }
    return 0;
}

 

posted on 2015-08-13 10:24  一个西瓜  阅读(173)  评论(0编辑  收藏  举报

导航