TheAlgorithms-C-Plus-Plus/math/extended_euclid_algorithm.cpp

31 lines
829 B
C++
Raw Normal View History

#include <iostream>
// Finding coefficients of a and b ie x and y in gcd(a, b) = a * x + b * y
// d is gcd(a, b)
// This is also used in finding Modular multiplicative inverse of a number.
// (A * B)%M == 1 Here B is the MMI of A for given M,
// so extendedEuclid (A, M) gives B.
2020-05-28 03:06:36 +08:00
template <typename T, typename T2>
void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) {
if (B > A) std::swap(A, B); // Ensure that A >= B
if (B == 0) {
2020-05-28 03:06:36 +08:00
*GCD = A;
*x = 1;
*y = 0;
} else {
2020-05-28 03:06:36 +08:00
extendedEuclid(B, A % B, GCD, x, y);
T2 temp = *x;
*x = *y;
*y = temp - (A / B) * (*y);
}
}
int main() {
2020-05-28 03:06:36 +08:00
uint32_t a, b, gcd;
int32_t x, y;
std::cin >> a >> b;
2020-05-28 03:06:36 +08:00
extendedEuclid(a, b, &gcd, &x, &y);
std::cout << gcd << " " << x << " " << y << std::endl;
return 0;
}