Created
February 1, 2016 17:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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