Last active
December 16, 2015 15:09
-
-
Save nevill/5453369 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
# to memorize the collatz sequence length for a specific number | |
memory = [] | |
Number::collatz = -> | |
if @ % 2 == 0 | |
@ / 2 | |
else | |
3 * @ + 1 | |
Number::collatzSequenceLength = -> | |
length = 0 | |
next = Number(@) | |
sequence = [] | |
# generate collatz sequence | |
while not memory[next] | |
sequence.push next | |
length++ | |
if next == 1 | |
break | |
else | |
next = next.collatz() | |
# memorize values | |
base = memory[next] || 0 | |
while value = sequence.shift() | |
memory[value] = length + base | |
length-- | |
memory[@] | |
maxLength = 0 | |
number = 0 | |
for value in [1000000..1] | |
continue if memory[value] > 0 | |
length = value.collatzSequenceLength() | |
if maxLength < length | |
maxLength = length | |
number = value | |
console.log "Max length: #{maxLength}" | |
console.log "Number: #{number}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment