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 or , it returns 1 (coprime).
- If , it returns .
- If , it recurses on .
- If , it recurses on .
This is the classic Euclidean algorithm by repeated subtraction, which computes .
For inputs and :
Since , is an exact multiple of . Repeatedly subtracting 15 from reduces by 15 in each step: .
When reaches 15, the condition x == y evaluates to true () and returns .
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.