Navigate back to the homepage

Program for Collatz Conjecture in JavaScript

Vishnu Damwala
May 3rd, 2020 · 1 min read

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

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

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

Examples

1function getCollatzConjectureSequence(value) {
2 if (value < 1) {
3 throw new Error('Only positive numbers are allowed')
4 }
5 let count = 0
6
7 console.log("Sequence starts");
8 console.log(value);
9
10 while (value > 1) {
11 value = value % 2 === 0 ?
12 value / 2 :
13 (3 * value) + 1;
14
15 console.log(value);
16
17 count++
18 }
19
20 console.log("Sequence ends");
21 console.log("Count", count);
22}
23
24getCollatzConjectureSequence(12)

Starting with n = 12, results in 9 steps

1Sequence starts
212
36
43
510
65
716
88
94
102
111
12Sequence ends
13Count 9

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

Happy coding

More articles from MeshWorld

Assignment operators in C

A tutorial showing the usage of assignment operators in C

April 12th, 2020 · 1 min read

JavaScript - String split() function

A tutorial showing the usage of split() function in JavaScript

April 5th, 2020 · 2 min read
© 2017–2020 MeshWorld
Link to $https://twitter.com/meshworldindiaLink to $https://facebook.com/meshworldindiaLink to $https://instagram.com/meshworld.india/