Drill

ProblemsJavaScript › warmup

Steps to reach one

easywarmupJavaScript

The Collatz rule: halve an even number, or triple an odd one and add one. Count how many steps it takes to land on 1.

collatzSteps(start: int) → int

Solve it in the editor →

Where you start

function collatzSteps(start) {
  
}

Worked examples

CallResult
collatzSteps(1)0
collatzSteps(6)8
collatzSteps(7)16
collatzSteps(27)111

Hint

A while loop that stops at 1, counting as it goes.

Reference solution in JavaScript
function collatzSteps(start) {
  if (start < 1) return -1;
  let n = start, steps = 0;
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    steps++;
  }
  return steps;
}

The same problem in another language

More warmup problems in JavaScript