Cod sursa(job #1259973)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 10 noiembrie 2014 19:15:48
Problema Invers modular Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include<fstream>

using namespace std;

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

int e( int n ) {
    int k, sol = n;
    k = n;
    for( int i = 2; i * i <= n; ++ i ) {
        if ( k % i == 0 ) {
            sol /= i;
            sol *= (i - 1);
            while ( k % i == 0 ) {
                k /= i;
            }
        }
    }
    if ( k > 1 ) {
        sol /= k;
        sol *= (k - 1);
    }
    return sol;
}
long long pow_log( long long a, int n, int x ) {
    long long sol;
    sol = 1;
    while ( n > 0 ) {
        if ( n % 2 == 1 ) {
            sol *= a;
            sol %= x;
        }
        a *= a; a %= x;
        n /= 2;
    }
    return sol ;
}
int main() {
    int a, n;
    fin >> a >> n;
    fout << pow_log( a, e( n ) - 1, n ) << "\n";
    fin.close();
    fout.close();
    return 0;
}