Extended Euclid Algorithm Recursive Solution

Extended Euclid Algorithm in C++ (Recursive Solution) with Step-by-Step Explanations:

#include <iostream>
using namespace std;

int extendedGCD(int a, int b, int &x, int &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    int x1, y1;
    int gcd = extendedGCD(b, a % b, x1, y1);
    x = y1;
    y = x1 - (a / b) * y1;
    return gcd;
}

int main() {
    int a = 30, b = 20;
    int x, y;
    int gcd = extendedGCD(a, b, x, y);
    cout << "GCD: " << gcd << ", x: " << x << ", y: " << y << endl;
    return 0;
}
  1. Include the necessary header files.

  2. Define a function extendedGCD that takes two integers a and b as input, along with references to x and y.

  3. In the extendedGCD function, check if b is 0. If true, set x to 1, y to 0, and return a.

  4. If b is not 0, declare variables x1 and y1.

  5. Call the extendedGCD function recursively with parameters b, a % b, x1, and y1, and store the result in gcd.

  6. Update x with the value of y1, and update y with the expression x1 - (a / b) * y1.

  7. Return the value of gcd.

  8. In the main function, define integers a and b.

  9. Declare variables x and y.

  10. Call the extendedGCD function with parameters a, b, x, and y, and store the result in gcd.

  11. Output the values of gcd, x, and y to the console.

  12. Return 0 to indicate successful completion of the program.