Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many integers n in [1, 100] reach 1 under the Collatz map within 10 steps? Run the code.

Problem: How many integers n in [1, 100] reach 1 under the Collatz map within 10 steps? Run the code.
def steps(n):
    c = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        c += 1
    return c
print(sum(1 for n in range(1, 101) if steps(n) <= 10))
What is printed?
  1. A. 20
  2. B. 2
  3. C. 25
  4. D. 22

Correct answer: D. 22

Exactly 22 starting values in 1..100 need at most 10 steps (n = 1 needs 0). Using a strict < 10 test gives 20, counting only those needing exactly 10 steps gives 2, and loosening the bound to 11 steps gives 25.

More Coding Interview Problems questions

Exams that ask this topic