Cod sursa(job #1698492)

Utilizator diana97Diana Ghinea diana97 Data 4 mai 2016 16:48:29
Problema Invers modular Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f ("inversmodular.in");
ofstream g ("inversmodular.out");

int n, mod;

int get_phi(int x) {
    int phi = x;

    while(x % 2 == 0) {
        x /= 2;
        phi /= 2;
    }

    for (int d = 3; d * d <= x; d += 2) {
        if (x % d != 0) continue;

        while(x % d == 0) {
            x = x / d;
            phi = phi / d * (d - 1);
        }
    }

    if (x != 1) phi = phi / x * (x - 1);
    return phi;
}

int putere(int x, int p, int mod) {
    if (p == 0) return 1;

    int aux = putere(x, p / 2, mod);
    if (p % 2) return (x * aux) % mod * aux % mod;
    return (aux * aux) % mod;
}

int main() {
    f >> n >> mod;
    int phi = get_phi(mod);
    g << putere(n, phi - 1, mod) << '\n';
    return 0;
}