Skip to main content

Collatz Steps

easy
Software engineer

The Collatz conjecture defines a process for any positive integer. Given an integer $n$, perform the following operations repeatedly until $n$ becomes $1$:

  • If $n$ is even, replace $n$ with $n / 2$.
  • If $n$ is odd, replace $n$ with $3n + 1$.

It is conjectured that this process will always reach $1$, no matter the starting value of $n$. Your task is to determine how many steps it takes for a given $n$ to reach $1$.

For example, if $n = 3$, the sequence is: $3 \rightarrow 10 \rightarrow 5 \rightarrow 16 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1$. This takes $7$ steps.

Example 1

Input

n = 6

Output

8

Explanation

The sequence for n = 6 proceeds as follows:
1. 6 is even → 3
2. 3 is odd → 10
3. 10 is even → 5
4. 5 is odd → 16
5. 16 is even → 8
6. 8 is even → 4
7. 4 is even → 2
8. 2 is even → 1
It takes 8 steps to reach 1.

Example 2

Input

n = 1

Output

0

Explanation

The number is already 1, so 0 steps are required.

Example 3

Input

n = 3

Output

7

Constraints

  • 1 <= n <= 10⁶

Screening

Hash TableMathMemoizationRecursionSimulation
Language
Code editor loads in the browser.

Output

Input

6

Expected

8

Your output

Run to see your output.