Cod sursa(job #2292957)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 30 noiembrie 2018 12:39:53
Problema Invers modular Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>

using namespace std;

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

int A, N;

int GetPhi(int x)
{
    if(x == 0 || x == 1)
        return 1;

    int phi = 1, xx = x;

    for(int i = 2; i * i <= xx; i++)
        if(xx % i == 0)
        {
            int primeFactor = i;
            int pow = 0;

            while(x % primeFactor == 0)
            {
                x /= primeFactor;
                pow++;

                if(pow == 1)
                    phi *= (primeFactor - 1);
                else
                    phi *= primeFactor;
            }
        }

    if(x)
        phi *= (x - 1);

    return phi;
}

int Power(int base, int exp)
{
    long long ans = 1;
    long long aux = base;

    for(int i = 1; i <= exp; i <<= 1)
    {
        if(i & exp)
            ans = ans * aux, ans %= N;

        aux = aux * aux, aux %= N;
    }

    return ans;
}

int main()
{
    fin >> A >> N;

    int phi = GetPhi(N);
    fout << Power(A, phi - 1);

    return 0;
}