Data Structures & AlgorithmsHardICPC regional · simulation

Problem: Starting from 27, the Collatz map is n -> n/2 if n is even and n -> 3n+1 if n is odd. How many steps does it take to first reach 1? Run the code.

Problem: Starting from 27, the Collatz map is n -> n/2 if n is even and n -> 3n+1 if n is odd. How many steps does it take to first reach 1? Run the code.
n = 27
steps = 0
while n != 1:
    n = n // 2 if n % 2 == 0 else 3 * n + 1
    steps += 1
print(steps)
What is printed?
  1. A. 112
  2. B. 110
  3. C. 111
  4. D. 96

Correct answer: C. 111

The trajectory of 27 is famously long, peaking at 9232 before reaching 1 after 111 steps. Off-by-one loops that stop at 2 give 110, which is the trap.

More Coding Interview Problems questions

Exams that ask this topic