beyondgrader.com Logo
DemoBrowseAboutTeamLogin

Collatz

ben@rigeltechnical.com // 1.0

The Collatz conjecture proposes that the below process will reach 1 regardless of the starting number:

  • If the current number is even, divide it by 2.
  • Otherwise, multiply the current number by 3 and add 1.

For example, starting with 5, it takes five steps to reach 1:

  • 5 is odd, so multiply it by 3 and add 1 to get 16.
  • 16 is even, so divide it by 2 to get 8.
  • 8 is even, so divide it by 2 to get 4.
  • 4 is even, so divide it by 2 to get 2.
  • 2 is even, so divide it by 2 to get 1.

Write a function collatz that takes an int parameter and returns how many steps of the Collatz process are required to get from it to 1. Assume that the parameter is always positive.