Skip to content

Instantly share code, notes, and snippets.

@giannispan
Created February 1, 2016 17:17
Show Gist options
  • Save giannispan/e59b72e12c6df94b5044 to your computer and use it in GitHub Desktop.
Save giannispan/e59b72e12c6df94b5044 to your computer and use it in GitHub Desktop.
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. If you repeat the process continously for n, n will eventually reach 1.
function collatz(n){
var i = 0, c = [];
c.push(n);
while (c[i] > 1) {
if (c[i] % 2 == 0) {
c.push(c[i] / 2);
}
else if (Math.abs(c[i] % 2) == 1) {
c[i] = (c[i] * 3) + 1;
c.push(c[i]);
}
i++ ;
}
return c.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment