GATE Computer ScienceHardGATE CS (PYQ pattern)

int g(int a, int b) { return b == 0 ? a : g(b, a % b); } How many calls to g (including the first) does g(610, 987) make, and how many does g(1000, 987) make?

  1. A. 15 and 5
  2. B. 16 and 6
  3. C. 14 and 4
  4. D. 16 and 5

Correct answer: D. 16 and 5

With a < b the first call only swaps (610 % 987 = 610), costing one extra call before the Fibonacci chain 987, 610, 377, ... , 1, 0, which takes 15 calls from g(987, 610). So g(610, 987) makes 16. g(1000, 987) -> g(987, 13) -> g(13, 12) -> g(12, 1) -> g(1, 0): 5 calls.

More Programming and Data Structures (GATE) questions

Exams that ask this topic