Back to questions

Collatz Sequence Steps Bloomberg Python Interview Question

Collatz Sequence Steps

Bloomberg Python Interview Question

Given a positive integer nn, the Collatz sequence for nn is generated by repeatedly applying the following operations:

  1. If nn is even, then n=n/2n = n / 2.
  2. If nn is odd, then n=3n+1n = 3 * n + 1.
  3. Repeat the above steps until nn becomes 1.

Your task is to return the number of steps required to reduce nn to 1.

Example #1

Input: n=3n = 3

Output: 7

Explanation:

The output is 7, because there were 7 Collatz steps taken:

3 ─> 10 ─> 5 ─> 16 ─> 8 ─> 4 ─> 2 ─> 1

Here's the math behind the 7 steps:

  1. Given 3 is odd, so 3n+1=103 * n + 1 = 10

  2. Given 10 is even, so n/2=5n / 2 = 5

  3. Given 5 is odd, so 3n+1=163 * n + 1 = 16

  4. Given 16 is even, so n/2=8n / 2 = 8

  5. Given 8 is even, so n/2=4n / 2 = 4

  6. Given 4 is even, so n/2=2n / 2 = 2

  7. Given 2 is even, so n/2=1n / 2 = 1

Input

Python

Output