Question

Consider the following ANSI C function:

int SomeFunction(int x, int y)
{
    if ((x == 1) || (y == 1)) return 1;
    if (x == y) return x;
    if (x > y) return SomeFunction(x - y, y);
    if (y > x) return SomeFunction(x, y - x);
}

The value returned by SomeFunction(15, 255) is ______.

Official answer and solution
Official answer
15
From
Official GATE 2021 answer key

Solution

Recognize the recursive function as Euclid's subtraction-based algorithm for finding the greatest common divisor (GCD).

Analyzing SomeFunction(x, y):

  • If x=1x=1 or y=1y=1, it returns 1 (coprime).
  • If x=yx=y, it returns xx.
  • If x>yx > y, it recurses on (x−y,y)(x - y, y).
  • If y>xy > x, it recurses on (x,y−x)(x, y - x).

This is the classic Euclidean algorithm by repeated subtraction, which computes gcd⁡(x,y)\gcd(x, y).

For inputs x=15x = 15 and y=255y = 255:
Since 255=15×17255 = 15 \times 17, yy is an exact multiple of xx. Repeatedly subtracting 15 from yy reduces yy by 15 in each step: 255→240→225⋯→15255 \to 240 \to 225 \dots \to 15.

When yy reaches 15, the condition x == y evaluates to true (15==1515 == 15) and returns 1515.

Final answer

15

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2021 Computer Science and Information Technology - Session 2 (CS2)
Question
33 of 65, printed as CS Q.23
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.