Cod sursa(job #2450444)

Utilizator Alex18maiAlex Enache Alex18mai Data 23 august 2019 12:55:46
Problema Invers modular Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
//ALEX ENACHE

#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <time.h>
#include <iomanip>
#include <deque>
#include <math.h>
#include <assert.h>
#include <stack>
#include <bitset>
#include <random>

using namespace std;

//-----------------------------------------------------------------

#include <fstream>

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

void euclid(long long a, long long b, long long& d, long long& x, long long& y) {
	if (b == 0) {
		d = a; // am ajuns la gcd
		x = 1; y = 0; // gcd * 1 + 0 = gcd (normal)

		// << a << " " << b << " " << d << " " << x << " " << y << '\n';
	}
	else {
		long long x0, y0; //acestea vor fi val pt b , a % b
		euclid(b, a % b, d, x0, y0);

		//x0 * b + y0 * (a%b) = d
		//a%b = a - (a/b) * b
		//x0 * b + y0 * (a - (a/b) * b) = d
		//y0 * a + (x0 - y0 * (a/b)) * b = d

		x = y0;
		y = x0 - (a / b) * y0;

		//cout << a << " " << b << " " << d << " " << x << " " << y << '\n';
	}
}

int main() {

	long long a, b, d, x, y;
	cin >> a >> b;
	euclid(a, b, d, x, y);
	x = (x%b + b) % b;
	cout << x;

	return 0;
}