25 XP

43. Collatz steps

Beginner loops math

Start with a whole number and keep applying one rule:

  • if the number is even, halve it;
  • if it is odd, multiply it by 3 and add 1.

Every number anyone has tried ends up at 1 sooner or later (nobody has proved that all of them do). Starting from 6, the numbers go 6, 3, 10, 5, 16, 8, 4, 2, 1: that's 8 steps.

Write a function collatz_steps(n) that takes a whole number n and returns how many steps it takes to reach 1. A step is one use of the rule, so n = 1 takes 0 steps.

Example 1

Inputn = 6
Output8
Explanation6, 3, 10, 5, 16, 8, 4, 2, 1: 8 steps.

Example 2

Inputn = 1
Output0
ExplanationAlready at 1.

Example 3

Inputn = 7
Output16
Explanation7 climbs as high as 52 before coming down.

Constraints

  • n is a whole number from 1 to 10,000.

Submit also runs 6 more tests you can't see.

Practises While Loops (lesson 14).

Code
def collatz_steps(n):
    """Count the steps from n down to 1.

    n: int, 1 or more
    Returns: int, how many times the rule is applied
        before n becomes 1
    """
    # Write your code here
    pass