Problems › TypeScript › warmup
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
Where you start
function collatzSteps(start: number): number {
}
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 TypeScript
function collatzSteps(start: number): number {
if (start < 1) return -1;
let n = start;
let steps = 0;
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
steps++;
}
return steps;
}