ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)
Function g(Integer n)
    if (n == 0)
        return 0
    end if
    return n mod 3 + 10 * g(n / 3)
End Function

Print g(50)
  1. A. 1221
  2. B. 2121
  3. C. 1212
  4. D. 212

Correct answer: C. 1212

g writes n in base 3, with the digits shown as a decimal number. 50 = 1×27 + 2×9 + 1×3 + 2, which is 1212₃. Reading the remainders in the order they come out (2, 1, 2, 1) gives the trap 2121.

More Pseudocode and Code Tracing questions

Exams that ask this topic