ProgrammingHardTCS NQT Advanced · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer calls = 0
Function f(Integer a, Integer b)
    calls = calls + 1
    if (b == 0)
        return a
    end if
    return f(b, a mod b)
End Function
Integer g = f(21, 34)
Print g, calls
  1. A. 1 8
  2. B. 1 10
  3. C. 1 9
  4. D. 7 9

Correct answer: C. 1 9

When a < b the first call just swaps them: f(21, 34) → f(34, 21). Then 34, 21, 13, 8, 5, 3, 2, 1, 0 follow the Fibonacci numbers down. Counting every call from f(21, 34) to f(1, 0) gives 9: output 1 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic