Pagini recente » Cod sursa (job #30166) | Cod sursa (job #1753809) | Cod sursa (job #744043) | Cod sursa (job #987992) | Cod sursa (job #3249891)
#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;
}