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:

• 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

`.css-1chxjt6{position:absolute;right:22px;top:24px;padding:8px 12px 7px;border-radius:5px;color:#6f7177;-webkit-transition:background 0.3s ease;transition:background 0.3s ease;}.css-1chxjt6:hover{background:rgba(255,255,255,0.07);}.css-1chxjt6[data-a11y="true"]:focus::after{content:"";position:absolute;left:-2%;top:-2%;width:104%;height:104%;border:2px solid var(--theme-ui-colors-accent,#6166DC);border-radius:5px;background:rgba(255,255,255,0.01);}@media (max-width:45.9375em){.css-1chxjt6{display:none;}}1Step 1: Start2Step 2: Declare variables n.3Step 3: Read n from the user.4Step 4: Repeat the steps until n > 15        4.1 If n % 2 === 06                n = n / 27            Else8                n = 3 * n + 19Step 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 = 067    console.log("Sequence starts");8    console.log(value);910    while (value > 1) {11        value = value % 2 === 0 ?12            value / 2 :13            (3 * value) + 1;1415        console.log(value);1617        count++18    }1920    console.log("Sequence ends");21    console.log("Count", count);22}2324getCollatzConjectureSequence(12)`

Starting with n = 12, results in 9 steps

`1Sequence starts212364351065716889410211112Sequence ends13Count 9`

Happy coding

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