Last Updated: 4 Dec, 2021

Extended Euclidean Algorithm

Moderate
Asked in companies
UberGoogle inc

Problem statement

You have just been taught about linear equations and about GCD(Greatest Common Divisor). So, you are given an equation AX + BY = C where A and B are two integers that you are given and D is the GCD or greatest common divisors of A and B.


So, you have to find out 2 integers x and y such that the above equation is satisfied for C = D, |X+Y| is minimum. If there are multiple such pairs, return the one where X is maximum.


Example:-
A = 2
B = 4
The answer should be D = 2 [gcd of (2,4)] and X = 1  and Y = 0 (|X+Y|=1 is the minimum possible value that can be obtained here).
Input Format :
The first line contains a single integer ‘T’ representing the number of test cases. Then each test case follows.

The first line of every test case contains two integers ‘A’ and ‘B’ denoting the 2 coefficients.
Output Format :
For each test case, print three integers ‘D’, ‘X’, and ‘Y’ where ‘D’ is the gcd of ‘A’ and ‘B’ and ‘X’ and ‘Y’ are the two coefficients that satisfy the equation AX + BY = D.

The output of each test case should be printed in a separate line.
Note :
You are not required to print anything, it has already been taken care of. Just implement the function.    
Constraints :
1 <= T <= 10
1 <= A <= 10^9
1 <= B <= 10^9

Time Limit = 1 sec

Approaches

01 Approach

Use the Euclidean algorithm to find the gcd of A and B first and then use the extended euclidean algorithm to find the coefficients of the equation.

 

More about Euclidean algorithm - https://cp-algorithms.com/algebra/euclid-algorithm.html

 

Algorithm:-

 

  1. Define a function named extended_euclidean_algo with A and B as parameters.
    1. If A is equal to 0, return the tuple (B, 0, 1).
    2. Else store the value returned by euclidean_algo with B%A and A as parameters in D, X, and Y.
    3. Update X as Y minus b divided by a multiplied by X.
    4. Update Y as X.
  2. Store the value returned by euclidean_algo with A and B as parameters in D, X, and Y.
  3. Return D, X, and Y.