extended euclid algorithm Algorithm

The Extended Euclid Algorithm is an extension of the Euclidean Algorithm, which efficiently computes the Greatest Common Divisor (GCD) of two integers. The algorithm is based on the principle that the GCD of two numbers does not change if the larger number is replaced by its difference with the smaller number. In addition to computing the GCD of two integers, the Extended Euclid Algorithm also finds integer coefficients such that the linear combination of the two numbers, i.e., ax + by, equals their GCD, where a and b are the given integers, and x and y are the coefficients to be determined. This property is particularly useful in various applications, including modular inverse calculation, Diophantine equation solving, and cryptography. The Extended Euclid Algorithm follows a recursive approach, similar to that of the basic Euclidean Algorithm. It starts with the base case, i.e., when one of the numbers is 0, the GCD is the other number, and the coefficients are 1 and 0, respectively. For other cases, the algorithm recursively calls itself with the smaller number and the remainder of the division of the larger number by the smaller number. It then updates the coefficients using the results of the recursive calls. The algorithm terminates when the remainder becomes 0, returning the GCD and the corresponding coefficients. Due to its efficient and recursive nature, the Extended Euclid Algorithm is widely used in computer programming and number theory for solving various problems involving integer arithmetic and modular systems.
#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.

int d, x, y;
void extendedEuclid(int A, int B) {
    if (B == 0) {
        d = A;
        x = 1;
        y = 0;
    } else {
        extendedEuclid(B, A%B);
        int temp = x;
        x = y;
        y = temp - (A/B)*y;
    }
}

int main() {
    int a, b;
    std::cin >> a >> b;
    extendedEuclid(a, b);
    std::cout << x << " " << y << std::endl;
    return 0;
}

LANGUAGE:

DARK MODE: