Cod sursa(job #3349979)

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

using namespace std;

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

int a, n;

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

int main()
{
    fin >> a >> n;
    long long 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;
}