Collatz conjecture (Ulam conjecture or the Syracuse problem)

The Collatz conjecture (also known as the Ulam conjecture or the Syracuse problem) is an unsolved mathematical problem, which is very easy to formulate:

1. Take any natural number
2. If it's even, half it, otherwise triple it and add one
3. Repeat step 2. until you reach 4, 2, 1 sequence
4. You will ALWAYS reach 1, eventually.
(using node js)

Video: https://youtu.be/jo_jxzrUsJ4

process.stdin.setEncoding('utf-8');

console.log('Please enter a number. \nTo exit enter: q');
process.stdin.on('data', (data) => {
if (data == 'q\n') {
process.exit();
}
if (isNaN(data)) {
console.log('Enter valid number');
}
let givenNumber = parseInt(data);
let number = '';
while (true) {
if (givenNumber % 2 === 0) {
console.log(givenNumber + ' / ' + 2 + ' = ' + givenNumber / 2);
givenNumber = givenNumber / 2;
} else {
console.log(givenNumber + ' * ' + 3 + ' + ' + 1 + ' = ' + ((givenNumber * 3) + 1));
givenNumber = (givenNumber * 3) + 1;
}
if (givenNumber === 4) {
number += 4;
}
if (givenNumber === 2) {
if (number === '4') {
number += 2;
}
}
if (givenNumber === 1) {
if (number === '42') {
number += 1;
}
}
if (number === '421') {
process.exit();
}
}
})

Output:


Comments

  1. let m =1;
    let trueFlag=true;
    let array=[];
    while(trueFlag){
    let n=m;
    f(n)
    }

    function f(n) {
    let sol;
    if(n%2===0){
    sol = n/2;
    }else{
    sol= 3*n+1;
    }
    console.log(sol);
    let flag=array.indexOf(sol);
    if(flag===-1){
    array.push(sol);
    }else{
    array.splice(flag,1);
    array.push(sol);
    }
    m=sol;
    if(array.indexOf(4)>=0 && array.indexOf(2)>=0 && array.indexOf(1)>=0 ){
    if(array.indexOf(4)<array.indexOf(1) && array.indexOf(4)<array.indexOf(2) && array.indexOf(2)<array.indexOf(1)){
    trueFlag = false;
    }
    }
    }

    ReplyDelete
    Replies
    1. That doesn't work if user has entered 4 or 2.

      Delete
  2. Okay then...

    This might sound pretty weird, and maybe even kind of "strange"

    WHAT if you could simply hit "Play" to LISTEN to a short, "miracle tone"...

    And suddenly bring MORE MONEY into your LIFE??

    What I'm talking about is hundreds... even thousands of dollars!!

    Sound too EASY?? Think it's IMPOSSIBLE?!?

    Well then, I've got news for you..

    Many times the most significant miracles in life are the easiest to GET!!

    In fact, I will provide you with PROOF by allowing you to listen to a real-life "miracle money tone" I developed...

    And do it FREE (no strings attached).

    YOU simply push "Play" and watch as your abundance angels fly into your life.. starting almost INSTANTLY..

    CLICK here NOW to experience the mysterious "Miracle Abundance Tone" as my gift to you!!

    ReplyDelete

Post a Comment

Popular Posts