920G - List Of Integers - CodeForces Solution


binary search bitmasks brute force combinatorics math number theory *2200

Please click on ads to support us..

C++ Code:

#include <vector>
#include <cstring>
#include <iostream>

const int maxn = 1.8e7;
bool pr[maxn + 100];
std::vector<long long> pint, f;

void fac(int x) {
  f.clear();
  for (auto i : pint) {
    if (x % i != 0)
      continue;
    if (i * i > x)
      break;
    f.push_back(i);
    while (x % i == 0)
      x /= i;
  }
  if (x != 1)
    f.push_back(x);
}

int solve(int val) {
  int ret = 0;
  int lim = 1 << f.size();
  for (int j = 1; j < lim; j++) {
    int tp = 1, ct = 0;
    for (int i = 0; i < (int)f.size(); i++) {
      if ((j >> i) & 1) {
        tp *= f[i];
        ct++;
      }
    }
    ret += (ct % 2 ? 1 : -1) * val / tp;
  }
  return val - ret;
}

int main() {
  std::memset(pr, true, sizeof(pr));
  pr[0] = pr[1] = false;
  for (int i = 2; i * i <= maxn; i++)
    if (pr[i])
      for (int j = i * i; j <= maxn; j += i)
        pr[j] = false;
  for (int i = 2; i <= maxn; i++)
    if (pr[i])
      pint.push_back(i);
  int cas, x, p, k;
  std::cin >> cas;
  while (cas--) {
    std::cin >> x >> p >> k;
    fac(p);
    int a1 = solve(x), L = x + 1, R = maxn, ans = 0;
    while (L <= R) {
      int mid = L + (R - L) / 2;
      int val = solve(mid) - a1;
      if (val >= k)
        R = mid - 1, ans = mid;
      else
        L = mid + 1;
    }
    std::cout << ans << "\n";
  }
  return 0;
}
// GURNfUXbeFUgWADpjlcjThLMPrjzNxYlxnsXimJDsEcsnXlOdFiUvDGOYjALGsPKLFGSsdmhVGgNCFyjeGJoXlzMcZzpEhCtWcQVpvajxWGEkejTwSLZbwDXWXsAqTYM


Comments

Submit
0 Comments
More Questions

325A - Square and Rectangles
1674F - Desktop Rearrangement
1140A - Detective Book
899A - Splitting in Teams
343A - Rational Resistance
1437D - Minimal Height Tree
1100C - NN and the Optical Illusion
1102E - Monotonic Renumeration
1682B - AND Sorting
1178C - Tiles
733C - Epidemic in Monstropolis
15C - Industrial Nim
40A - Find Color
1696E - Placing Jinas
700A - As Fast As Possible
1331C - And after happily lived ever they
1468J - Road Reform
1361B - Johnny and Grandmaster
1151A - Maxim and Biology
1472E - Correct Placement
1388B - Captain Flint and a Long Voyage
898C - Phone Numbers
558A - Lala Land and Apple Trees
534C - Polycarpus' Dice
368A - Sereja and Coat Rack
1279C - Stack of Presents
1380C - Create The Teams
1228B - Filling the Grid
940C - Phone Numbers
1701C - Schedule Management