Editor

Collatz Steps

#214 · Loops · Beginner · 30 XP · about 5 min

Pick any positive whole number and apply this rule to it again and again:

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

Nobody has ever proved it, but every number anyone has tried eventually reaches 1. Write collatz_steps(n) that returns how many times the rule is applied before n reaches 1.

Examples

collatz_steps(6)  # returns 8
collatz_steps(1)  # returns 0
collatz_steps(7)  # returns 16

From 6 the numbers are 6, 3, 10, 5, 16, 8, 4, 2, 1: that is 8 steps. If n is already 1, no steps are needed.

Constraints

  • 1 <= n <= 10 ** 13

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.