Counting steps to one — Pseudocode Aptitude Question
Counting steps to one: / is integer division. How many times does the body of the loop run? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 180 seconds
Question
/ is integer division. How many times does the body of the loop run?
Integer n, steps
Set n = 7
Set steps = 0
While n != 1
If n MOD 2 == 0 Then
Set n = n / 2
Else
Set n = 3 * n + 1
End If
Set steps = steps + 1
End While
Print stepsOptions
- 11
- 14
- 16
- 17
Show the answer and the worked solution
Correct answer: C. 16
Worked solution
- The chain is 7 → 22 → 11 → 34 → 17 → 52 → 26 → 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1.
- Each arrow is one pass of the loop, and there are 16 arrows.
- The loop then finds n = 1 and stops, so 16 is printed.
Answer: 16.
The idea
Halve when even, triple and add one when odd. There is no shortcut: write the chain out carefully, and remember that the number of steps is one less than the number of values listed.
Shortcut. Once the chain reaches 16 = 2⁴, exactly four halvings remain; 7 reaches 16 on step 12, so the total is 12 + 4 = 16.
Common trap. 17 counts the values in the chain from 7 to 1 rather than the arrows between them; the first value costs no pass of the loop.