Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE

Problem: Start with x = 5. Repeat this rule: if x is odd, set x = x + 3; if x is even, set x = 2x − 1. Count how many times the rule is applied until x first becomes at least 500. How many applications are needed?

  1. A. 12
  2. B. 7
  3. C. 13
  4. D. The value never reaches 500

Correct answer: A. 12

The trajectory is 5, 8, 15, 18, 35, 38, 75, 78, 155, 158, 315, 318, 635, so 12 applications. Using 2x instead of 2x − 1 doubles straight to 512 in 7 steps, counting the values (including the start) gives 13, and misreading the even rule as x / 2 traps x in the loop 8, 4, 2, 1, 4, …

More Coding Interview Problems questions

Exams that ask this topic