Collatz Sequence Length Counter

Hard ⏱ 18 min 39% acceptance ★★★★★ 4.9
Write a function collatz_length(n) that returns the number of steps it takes for the Collatz sequence starting at n to reach 1. The rule: if the current value is even, divide by 2; if odd, multiply by 3 and add 1. Count each transformation as one step (reaching 1 itself is not counted as an extra step if n starts at 1, which takes 0 steps).

Examples

Example 1
Input
collatz_length(6)
Output
8
Explanation

6->3->10->5->16->8->4->2->1 is 8 steps.

Example 2
Input
collatz_length(1)
Output
0
Explanation

Already at 1, so zero steps are needed.

Constraints

  • n is a positive integer.

Topics

Loopswhile loop

Companies

MetaIntel

Hints

Hint 1

Use a while loop that continues as long as the current value is not 1.

Hint 2

Increment a step counter on each transformation.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.