Drill

ProblemsC# › warmup

Steps to reach one

easywarmupMathSimulationC#

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

C# 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

public 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 C#
public 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 C#