Problem 155258 · easy · Phase 01 Prerequisites & Setup

Collatz Steps

while loop · conditionals · counters

Start with a positive integer n and repeat this rule until you reach 1:

  • if n is even, replace it with n // 2
  • if n is odd, replace it with 3 * n + 1

Nobody has proved that this always reaches 1, but it does for every number anyone has tried. Write a function collatz_steps(n) that returns how many steps it takes to reach 1.

Examples

Input:  n = 6
Output: 8
Explanation: 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 takes 8 steps.
Input:  n = 1
Output: 0
Explanation: We are already at 1, so no steps are needed.

Constraints

  • 1 <= n <= 10000

Goals

  • Repeat a block of code with a while loop until a condition becomes false
  • Update a variable inside a loop and keep a separate counter
  • Decide between two updates with an if/else inside a loop
Starting Python…