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 f(Integer n)
    if (n == 0)
        return 0
    end if
    if (n mod 2 == 1)
        return 1 + f(n - 1)
    end if
    return 1 + f(n / 2)
End Function

Print f(29)
  1. A. 9
  2. B. 5
  3. C. 4
  4. D. 8

Correct answer: D. 8

29 → 28 → 14 → 7 → 6 → 3 → 2 → 1 → 0 takes 8 steps. In general it is (number of bits - 1) + (number of 1-bits) = 4 + 4. Counting only the 1-bits gives 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic