Skip to content
Exercise · Loops · lesson 8 of 8

Exercise: Collatz steps

A Collatz step changes a number as follows. An even number is divided by 2, and an odd n is replaced with 3 * n + 1. Write a function int collatz_steps(int n) that returns how many such steps it takes to get from n to 1.

  • collatz_steps(6) → 8: 6, 3, 10, 5, 16, 8, 4, 2, 1
  • collatz_steps(27) → 111
  • collatz_steps(1) → 0

Constraints: n is from 1 to 10000; every intermediate number fits in an int.

collatz.cpp — cpp
cpp · 4 lines
Ctrl+Enter run · Esc leave editor