Cod sursa(job #3349978)

Utilizator GavrilitaIanisGavrilita Ianis GavrilitaIanis Data 4 aprilie 2026 11:11:31
Problema Invers modular Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <bits/stdc++.h>

using namespace std;

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

int a, n;

int ExpoFast(int a, int p)
{
    if(p == 0)
        return 1;
    if(p % 2 == 0)
    {
        int rez = ExpoFast(a, p / 2);
        return (rez * rez) % n;
    }
    else
    {
        int rez = ExpoFast(a, p / 2);
        return (a * rez * rez) % n;
    }
}

int main()
{
    fin >> a >> n;
    int f, p = n;
    for(f = 2; f * f <= n; f++)
        if(n % f == 0)
        {
            p *= (f - 1);
            p /= f;
            while(n % f == 0)
                n /= f;

        }
    if(n != 1)
    {
        p *= (n - 1);
        p /= n;
    }
    fout << ExpoFast(a, p - 1) % n << "\n";
    return 0;
}