Cod sursa(job #3125630)

Utilizator TheRomulusIvan Remus TheRomulus Data 3 mai 2023 21:50:22
Problema Invers modular Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <stdio.h>
#include <fstream>

#define ll long long

using namespace std;

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

void recursiveGCD(ll& x, ll& y, ll a, ll b)
{
    if (!b)
        x = 1, y = 0;
    else
    {
        recursiveGCD(x, y, b, a % b);
        ll aux = x;
        x = y;
        y = aux - y * (a / b);
    }
}

/*
* Compute B such that A*B = 1 % N
*/
ll computeModularInverse(ll A,ll N) {
    ll inv = 0, ins;

    recursiveGCD(inv, ins, A, N);

    if (inv <= 0)
        inv = N + inv % N;

    return inv;
}

int main()
{
    ios_base::sync_with_stdio(false);

    ll A, N;

    fin >> A >> N;
    
    ll modularInverse = computeModularInverse(A, N);

    fout << modularInverse;

    return 0;
}