(no title)
gluelogic | 6 years ago
I am a web dev who knows nothing of the Collatz conjecture, so I had to check out the Wikipedia article for it. Thanks for teaching me something today.
I wrote this JavaScript function based on what I read in the article. It's a simple algorithm but it was fun to see it work. For anyone who is in my shoes (weak mathematical background), running this function might be a useful supplement for illustrating the gist concept of the Collatz conjecture:
function collatz(i) {
console.log(i); // for visual feedback
if (i <= 0) throw new Error('Input must be a positive integer');
if (i === 1) return i;
if (i % 2 === 0) return collatz(i/2);
return collatz((3*i)+1);
}
collatz(42); // or any positive integer
No comments yet.