Cod sursa(job #1963107)

Utilizator tziplea_stefanTiplea Stefan tziplea_stefan Data 12 aprilie 2017 12:01:53
Problema Frac Scor 100
Compilator cpp Status done
Runda trainingtsa3 Marime 1.54 kb
#include <fstream>
#include <vector>
#define VAL 109545
#define DIVIZ 45
#define LL long long

using namespace std;

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

int K;
LL N, P;
LL DIV[DIVIZ];
bool ok[VAL];
vector<LL> prim;
vector<LL> :: iterator it;

void Sieve()
{
    LL i, j;
    for (i=2; i<VAL; i++)
    {
        if (ok[i]==false)
        {
            prim.push_back(i);
            for (j=i*i; j<VAL; j+=i)
              ok[j]=true;
        }
    }
}

void Decompose()
{
    for (it=prim.begin(); it!=prim.end() && (*it)*(*it)<=N; it++)
    {
        if (N % (*it)==0)
        {
            DIV[K++]=*it;
            while (N % (*it)==0)
              N/=*it;
        }
        if (N==1)
          break;
    }
    if (N>1)
      DIV[K++]=N;
}

LL Verify(LL X)
{
    int i, j, cnt;
    LL ANS=0, Prod;
    for (i=1; i<(1 << K); i++)
    {
        Prod=1;
        cnt=0;
        for (j=0; j<K; j++)
        {
            if ((i & (1 << j))!=0)
            {
                cnt++;
                Prod*=DIV[j];
            }
        }
        if (cnt % 2==1)
          ANS+=X / Prod;
        else
          ANS-=X / Prod;
    }
    return X-ANS;
}

LL Binary_Search()
{
    LL be=1, en=1LL << 61;
    LL mid, ans=0;
    while (be<=en)
    {
        mid=(be+en) / 2;
        if (Verify(mid)>=P)
        {
            ans=mid;
            en=mid-1;
        }
        else
          be=mid+1;
    }
    return ans;
}

int main()
{
    fin >> N >> P;
    Sieve();
    Decompose();
    fout << Binary_Search() << '\n';
    fin.close();
    fout.close();
    return 0;
}