Drill

ProblemsJava › warmup

Steps to reach one

easywarmupMathSimulationJava

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

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int collatzSteps(int 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 Java
int collatzSteps(int start) {
    if (start < 1) return -1;
    long n = start;
    int 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 Java