ProgrammingHardInfosys · Accenture pattern

What will be the output of the following pseudocode? (calls counts every call, including the first; mod is the remainder.)

What will be the output of the following pseudocode? (calls counts every call, including the first; mod is the remainder.)
Integer calls = 0
Function g(Integer a, Integer b)
    calls = calls + 1
    if (b == 0)
        return a
    end if
    return g(b, a mod b)
End Function
Print g(89, 55), calls
  1. A. 1 9
  2. B. 1 10
  3. C. 1 11
  4. D. 34 10

Correct answer: B. 1 10

Consecutive Fibonacci numbers are the worst case for Euclid: (89, 55) → (55, 34) → (34, 21) → (21, 13) → (13, 8) → (8, 5) → (5, 3) → (3, 2) → (2, 1) → (1, 0). That is 10 calls, the last one returning gcd = 1. Forgetting the final call with b = 0 gives 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic