Cod sursa(job #2426323)

Utilizator SemetgTemes George Semetg Data 27 mai 2019 13:51:32
Problema Principiul includerii si excluderii Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <vector>
using namespace std;
 
ifstream in { "pinex.in" };
ofstream out { "pinex.out" };

const int VAL_MAX { 1000000 };
 
int M;
int64_t A, B;
vector<int64_t> p;
int ciur[VAL_MAX + 5];
int64_t sol;
 
void init() {
    in >> M;
 
    for (int64_t i = 2; i * i <= VAL_MAX; ++i)
        if (!ciur[i]) 
            for (int64_t j { i * i }; j <= VAL_MAX; j += i)
                ciur[j] = false;
 
    for (int i { 2 }; i <= VAL_MAX; ++i)
        if (!ciur[i])
            p.push_back(i);
}
 
void solve() {
    vector<int> d;
    for (const auto& b : p) {
        if (b * b > B)
            break;
 
        if (B % b == 0) {
            d.push_back(b);
            while (B % b == 0)
                B /= b;
        }
    }
 
    if (B != 1)
        d.push_back(B);
 
    sol = 0;
    for (int config { 1 }; config < 1LL << d.size(); ++config) {
        int noSets { 0 };
        int64_t prod { 1 };
        for (int prime { 0 }; prime < d.size(); ++prime)
            if (config & (1 << prime)) {
                ++noSets;
                prod *= d[prime];
            }
 
        sol += (noSets % 2 ? 1 : -1) * (A / prod);
    }
}
 
int main() {
    init();
 
    while (M--) {
        in >> A >> B;
        solve();
        out << A - sol << '\n';
    }
}