Drill

ProblemsGo › warmup

Steps to reach one

easywarmupMathSimulationGo

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

Go 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

func collatzSteps(start int) int {
	
}

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 Go
func collatzSteps(start int) int {
	if start < 1 {
		return -1
	}
	n, steps := start, 0
	for n != 1 {
		if n%2 == 0 {
			n /= 2
		} else {
			n = 3*n + 1
		}
		steps++
	}
	return steps
}

The same problem in another language

More warmup problems in Go