ProgrammingHardTCS NQT · Accenture pattern

What will be the output? (calls counts every call, including the first.)

What will be the output? (calls counts every call, including the first.)
Integer calls = 0
Function fun(Integer a, Integer b)
    calls = calls + 1
    if (a == 0)
        return b
    end if
    return fun(b mod a, a)
End Function

Print fun(21, 13), calls
  1. A. 1 7
  2. B. 1 6
  3. C. 13 8
  4. D. 1 8

Correct answer: D. 1 8

The first call swaps the pair because 13 mod 21 = 13: (21,13) → (13,21) → (8,13) → (5,8) → (3,5) → (2,3) → (1,2) → (0,1). That is 8 calls, returning gcd = 1. Missing the first swap call gives 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic