ProgrammingHardAmazon OA · Infosys SP

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)
Integer n = 100, steps = 0
while (n > 1)
    if (n mod 2 == 0)
        n = n / 2
    else
        n = n - 1
    end if
    steps = steps + 1
end while
Print steps
  1. A. 6
  2. B. 8
  3. C. 2
  4. D. 9

Correct answer: B. 8

100 → 50 → 25 → 24 → 12 → 6 → 3 → 2 → 1: 8 steps. In binary (1100100) each bit after the first costs one halving (6) and each extra 1 bit costs one subtraction (2). 6 counts only the halvings, 2 only the subtractions, and 9 counts the 9 values visited instead of the moves.

More Pseudocode and Code Tracing questions

Exams that ask this topic