Cod sursa(job #2949883)

Utilizator LukyenDracea Lucian Lukyen Data 2 decembrie 2022 03:18:45
Problema Principiul includerii si excluderii Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("pinex.in");
ofstream fout("pinex.out");

vector<int> primes;
const int prime_max = 100000;

void getPrimes()
{
  bitset<100001> vis(false);
  primes.push_back(2);
  for (int i = 4; i <= prime_max; i += 2)
    vis[i] = true;

  for (int i = 3; i <= prime_max; i += 2)
    if (vis[i] == false)
    {
      primes.push_back(i);
      for (int j = i; j <= prime_max; j += i)
        vis[j] = true;
    }
}

int main()
{
  long long m;

  getPrimes();

  fin >> m;
  for (long long i = 1; i <= m; i++)
  {
    long long a, b;
    fin >> a >> b;

    vector<long long> divPrim;

    for (int div : primes)
      if (div > b)
      {
        break;
      }
      else if (b % div == 0)
      {
        divPrim.push_back(div);
        while (b % div == 0)
          b /= div;
      }

    long long res = 0, size = divPrim.size(), steps = 1 << size;
    for (long long i = 1; i < steps; i++)
    {
      long long temp = 1, cnt = 0;
      for (long long p = 0; p < size; p++)
        if (i & (1 << p))
          temp *= divPrim[p], cnt++;

      if (cnt % 2 != 0)
        res += a / temp;
      else
        res -= a / temp;
    }

    fout << a - res << "\n";
  }

  return 0;
}