GATE / CS ARCHIVE

GATE CSE 2021 SET 2 / QUESTION 23

GATE CSE 2021 Set 2 Q23

Programming in C · Recursion · Full GATE CSE 2021 Set 2 paper

GATE 2021 Set 2, Q23 1 mark · NAT
Report issue

Recursion

Question 23, GATE 2021: SomeFunction(x,y): if x==1 or y==1 return 1; if x==y return x; if x>y recurse on (x−y,y); if y>x recurse on (x,y−x). Find SomeFunction(15,255).
Tap to enlarge
Answer & solution

Official answer: 15

Step through it (19 steps)

Each recursive step subtracts the smaller positive argument from the larger, preserving their gcd. Starting at(15, 255), repeated subtraction reaches(15, 15), which returns 15. Neither argument reaches 1 on this input.

The invariant gcd(x,y)=gcd(x,y−x) explains correctness, while decreasing x+y proves termination for positive integers. Here y successively becomes 240,225,…,30,15, after sixteen subtractions of 15, and the equality branch returns 15. A modulo-based Euclidean algorithm would skip these repeated subtraction calls.

Original paper, page 65 · Answer key