Steps to reach one
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.
- Starting at 1 takes no steps at all.
- A start below 1 is not a valid starting point: return -1.
- Every start given here reaches 1 well inside a 32-bit integer.
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.
Where you start
int collatzSteps(int start) {
}
Worked examples
| Call | Result |
|---|---|
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++
int collatzSteps(int start) {
if (start < 1) return -1;
long long n = start;
int steps = 0;
while (n != 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
return steps;
}