Cod sursa(job #1990491)

Utilizator MaligMamaliga cu smantana Malig Data 12 iunie 2017 09:08:08
Problema Invers modular Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <algorithm>

using namespace std;
ifstream in("inversmodular.in");
ofstream out("inversmodular.out");

#define ll long long
#define pb push_back
const int inf = 1e9 + 5;
const int NMax = 5e5 + 5;

ll A,N;

ll getPhi(ll);
ll pw(ll,ll);

int main() {

    in>>A>>N;
    ll phi = getPhi(N);

    out<<pw(A,phi-1)<<'\n';

    in.close();out.close();
    return 0;
}

ll getPhi(ll x) {
    ll ans = x;
    for (int i=2;i*i <= x;++i) {
        if (x % i != 0) {
            continue;
        }

        while (x & i == 0) {
            x /= i;
        }

        ans = ans * (i-1) / i;
    }
    if (x != 1) {
        ans = ans * (x-1) / x;
    }

    return ans;
}

ll pw(ll base,ll exp) {
    ll ans = 1;
    while (exp) {
        if (exp & 1) {
            ans = (ans * base) % N;
        }
        base = (base * base) % N;
        exp >>= 1;
    }

    return ans;
}