Cod sursa(job #3249891)

Utilizator juruAndreea Jurubescu juru Data 18 octombrie 2024 18:13:43
Problema Invers modular Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.65 kb
#include <fstream>

using namespace std;

ifstream cin("inversmodular.in");
ofstream cout("inversmodular.out");

int gcdExtended(int a, int b, int& x, int& y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    int x1 = 0, y1 = 0;
    int d = gcdExtended(b, a % b, x1, y1);
    x = y1;
    y = x1 - y1 * (a / b);
    return d;
}

int modInverse(int a, int M) {
    int x, y, mod;
    int g = gcdExtended(a, M, x, y);
    if(g != 1)
        mod = -1;
    else
        mod = (x % M + M) % M;
    return mod;
}

int main() {
    int a, N;
    cin >> a >> N;
    cout << modInverse(a, N);

    return 0;
}