Data Structures & AlgorithmsVery hardTCS CodeVita · Microsoft SDE OA

The recursive extended Euclidean algorithm eg(a, b) returns (g, x, y) with a·x + b·y = g, using eg(a, b) = (g, y, x − (a//b)·y) when b ≠ 0 and eg(a, 0) = (a, 1, 0). Run it on (240, 46) and print the x it returns.

The recursive extended Euclidean algorithm eg(a, b) returns (g, x, y) with a·x + b·y = g, using eg(a, b) = (g, y, x − (a//b)·y) when b ≠ 0 and eg(a, 0) = (a, 1, 0). Run it on (240, 46) and print the x it returns.
def eg(a,b):
    if b==0: return (a,1,0)
    g,x,y=eg(b,a%b)
    return (g,y,x-(a//b)*y)
print(eg(240,46)[1])
What is printed?
  1. A. 1
  2. B. 47
  3. C. 2
  4. D. -9

Correct answer: D. -9

The recursion returns a particular Bezout pair; swapping the arguments returns a different valid pair, and the y coefficient or the gcd itself is a different output. Only the exact recursion as written determines the printed value.

More Coding Interview Problems questions

Exams that ask this topic