poj2773 Happy 2006 二分+容斥

求第K个与M互质的数


#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <cstdio>
#include <algorithm>
#define N 10005
typedef long long LL;
using namespace std;
int n , K , f[128] , s , a[128] , cnt[128];

void init()
{
  int i ; s = 1;
  for (i = 2 ; i * i <= n ; ++ i)
    if (n % i == 0)
    {
      f[s] = i , s <<= 1;
      while (n % i == 0)
        n /= i;
    }
  if (n > 1) f[s] = n , s <<= 1;
  a[0] = 1 , cnt[0] = 0;
  for (i = 1 ; i < s ; ++ i)
    a[i] = a[i & (i - 1)] * f[i & -i] , cnt[i] = cnt[i >> 1] + (i & 1);
}

LL cal(LL m)
{
  int ans = 0;
  for (int i = 0 ; i < s ; ++ i)
    if (cnt[i] & 1)
      ans -= m / a[i];
    else ans += m / a[i];
  return ans;
}
void work()
{
  int l = 1 , r = 1000000000 , m;
  init();
  while (l < r)
  {
    m = (l + r) >> 1;
    if (cal(m) < K)
      l = m + 1;
    else r = m;
  }
  cout << l << endl;
}


int main()
{
  while(~scanf("%d%d",&n,&K))
    work();
  return 0;
}


你可能感兴趣的:(poj2773 Happy 2006 二分+容斥)