Last active
August 29, 2015 14:21
-
-
Save rs77/6060875c124638ec6931 to your computer and use it in GitHub Desktop.
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
// Every number can be reduced to 1 applying the following rules: | |
// If the number is even divide by two (halve it) | |
// If the number is odd multiply by 3 and add 1 | |
// Students were asked to find the largest "chain" from numbers 2 to 100. | |
// Answer is 97 (118) as shown by the following script, then 73 (115), then 54/55 (112). | |
// Exercise was done as a whole class. | |
var collatz = function(minNum, maxNum) { | |
var links = '', temp, steps; | |
for ( var i = minNum; i <= maxNum; i++ ) { | |
temp = i; | |
if ( temp > 1 ) { | |
steps = 1; | |
links = temp + " -> "; | |
while ( temp > 1 ) { | |
if ( temp % 2 === 0 ) { | |
temp = temp / 2; | |
} else { | |
temp = (3 * temp) + 1; | |
} | |
if ( temp > 1 ) { | |
links += temp + " -> "; | |
steps++; | |
} | |
} | |
} | |
console.log(links + "1" + " (" + (steps || "0") + ")"); | |
console.log(" "); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment