MeshWorld India LogoMeshWorld.

Program for Collatz Conjecture in JavaScript

Listen to ArticleAI Speech
~2 min read narration
100%
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

Reader Quality Feedback

Did this technical guide help solve your problem?

Suggest Errata ($0)
Vishnu
Primary Author

Vishnu

Founder & Principal Architect at MeshWorld. Senior engineer and instructor specializing in AI agent systems, scalable web architecture, and modern development workflows.

Explore Author Archive
Compute Fuel & Open Testbed
100% Independent & Verified

Fuel High-Density, Zero-Fluff Engineering Deep-Dives

Every guide on MeshWorld is validated on physical Linux nodes and reproducible testbeds. If this article saved you hours of debugging or unblocked production, consider funding our next cluster run.

Weekly Dispatch

Join MeshWorld Dispatch

Get practical tutorials, system blueprints, and curated AI engineering notes straight to your inbox. No fluff, zero spam.

Zero spam. 1-click unsubscribe anytime.Prefer RSS?
Curated Continuations

Up Next in This Domain.

Browse Full Archive