Cod sursa(job #2085024)

Utilizator alexge50alexX AleX alexge50 Data 9 decembrie 2017 16:01:24
Problema GFact Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.34 kb
#include <stdio.h>
#include <utility>
#include <vector>

typedef std::vector<std::pair<int, unsigned long long>> A;

bool BfactDivA(unsigned long long b, A &a);

int main()
{
    FILE *fin = fopen("gfact.in", "r"),
            *fout = fopen("gfact.out", "w");
    int p, q;
    int d;
    A a;

    fscanf(fin, "%d %d", &p, &q);

    d = 2;
    while(d * d <= p)
    {
        unsigned long long x = 0;
        while(p % d == 0)
        {
            p = p / d;
            x++;
        }

        if(x >= 0)
            a.emplace_back(d, x * q);

        d++;
    }

    if(p != 1)
        a.emplace_back(p, q);

    /*for(std::pair<int, int> x: a)
    {
        printf("%d %d\n", x.first, x.second);
    }*/


    unsigned long long int step = 1LL << 50;
    unsigned long long int r = 0;

    while (step != 0)
    {
        if(!BfactDivA(r + step, a))
            r += step;
        step /= 2LL;
    }

    fprintf(fout, "%llu", r + 1LL);

    fcloseall();
    return 0;
}

bool BfactDivA(unsigned long long int b, A &a)
{
    bool divides = true;
    for(std::pair<int, int> x: a)
    {
        unsigned long long int p;
        unsigned long long  n;

        n = 0;
        p = static_cast<unsigned int>(x.first);

        while(p <= b)
        {
            n += b / p;
            p *= x.first;
        }
        divides &= n >= x.second;
    }

    return divides;
}