Skip to content

Instantly share code, notes, and snippets.

@wizo06
Last active June 22, 2018 00:06
Show Gist options
  • Save wizo06/e700f103ec6f2103c1990c389d605cf7 to your computer and use it in GitHub Desktop.
Save wizo06/e700f103ec6f2103c1990c389d605cf7 to your computer and use it in GitHub Desktop.
To run: "node collatz.js <integer>". Collatz Conjecture in Javascript. Left column is the number of steps to get to 1.
// Warning: maximum value for a variable of type Number (no bitwise or shift operators allowed): 9,007,199,254,740,991
let x = parseInt(process.argv[2]);
if(isNaN(x)) process.exit(1);
else{
if(x < 1){
process.exit(1);
}
else{
let n = 0; console.log(`${n} ${x}`);
while (x !== 1){
if(x%2 === 0){
x = x/2; n++; console.log(`${n} ${x}`);
}
else{
x = (3*x)+1; n++; console.log(`${n} ${x}`);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment