Start with a positive integer n and repeat this rule until you reach 1:
- if
nis even, replace it withn // 2 - if
nis odd, replace it with3 * 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