ProgrammingHardTCS NQT · Accenture

Starting from n = 27, the Collatz step is applied: if n is even, n becomes n/2, otherwise n becomes 3n + 1. The procedure below counts the steps until n becomes 1. What is printed?

Starting from n = 27, the Collatz step is applied: if n is even, n becomes n/2, otherwise n becomes 3n + 1. The procedure below counts the steps until n becomes 1. What is printed?
steps = 0
while n != 1
    if n mod 2 == 0 then n = n div 2 else n = 3*n + 1
    steps = steps + 1
end while
Print steps
  1. A. 55
  2. B. 112
  3. C. 9232
  4. D. 111

Correct answer: D. 111

Starting at 27 the sequence takes 111 steps before reaching 1 and peaks at 9232. Printing half the step count gives 55, stopping the count one early gives 112, and printing the peak value 9232 answers a different question.

More Pseudocode and Code Tracing questions

Exams that ask this topic