Program for Collatz Conjecture in JavaScript

The Collatz Conjecture, also known as 3n + 1 conjecture, Ulam Conjecture, Thwaites conjecture, Hasse’s algorithm, Kakutani’s problem, or the Syracuse problem, is a conclusion formed on the basis of incomplete information in mathematics

The Collatz Conjecture is an eventually one of the unsolved problem in mathematics and applying the following algorithm to any number we will always eventually reach one. It can be summarized as follows:

  • Start with any positive integer.
  • Each new term is obtained from the previous term:
    • If the previous term is even, the next term is half of the previous term i.e (previous / 2).
    • If the previous term is odd, the next term is 3 times the previous term plus 1 i.e (3 * previous + 1).
  • Repeat the process indefinitely. No matter what value of n is, the sequence will always reach 1.

Algorithm

Step 1: Start
Step 2: Declare variables n.
Step 3: Read n from the user.
Step 4: Repeat the steps until n > 1
        4.1 If n % 2 === 0
                n = n / 2
            Else
                n = 3 * n + 1
Step 5: Stop

Given a number n, return the number of steps required to reach 1.

Examples

function getCollatzConjectureSequence(value) {
  if (value < 1) {
    throw new Error("Only positive numbers are allowed");
  }
  let count = 0;

  console.log("Sequence starts");
  console.log(value);

  while (value > 1) {
    value = value % 2 === 0 ? value / 2 : 3 * value + 1;

    console.log(value);

    count++;
  }

  console.log("Sequence ends");
  console.log("Count", count);
}

getCollatzConjectureSequence(12);

Starting with n = 12, results in 9 steps

Sequence starts
12
6
3
10
5
16
8
4
2
1
Sequence ends
Count 9

Hope you learn something new. If this article was helpful, share it.

Happy coding

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳