← Back to challenges

3n + 1 Problem (Collatz Conjecture)

JavaScriptHardloopsnumbers

Instructions

A Collatz sequence is generated by repeatedly applying the following rules to an integer and then to each resulting integer in turn:

  • If even: divide by 2.
  • If odd: multiply by 3, then add 1.

The Collatz algorithm has been tested and found to always reach 1 for all positive integers.

Create a function that, when given two positive integers a b, returns the string "a" if integer a took fewer steps to reach 1 than b when passed through the Collatz sequence, or "b" if integer b took fewer steps to reach 1 than a.

Examples

collatz(10, 15) ➞ "a"
// Because 10.0 - 5.0 - 16.0 - 8.0 - 4.0 - 2.0 - 1.0: 6 steps
// 15.0 - 46.0 - 23.0 - 70.0 - 35.0 - 106.0 - 53.0 - 160.0 - 80.0 - 40.0 - 20.0 - 10.0 - 5.0 - 16.0 - 8.0 - 4.0 - 2.0 - 1.0: 17 steps

collatz(13, 16) ➞ "b"

collatz(53782, 72534) ➞ "b"

Notes

Assume a and b never take the same number of steps to reach 1.

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.