Skip to content

Instantly share code, notes, and snippets.

@nevill
Last active December 16, 2015 15:09
Show Gist options
  • Save nevill/5453369 to your computer and use it in GitHub Desktop.
Save nevill/5453369 to your computer and use it in GitHub Desktop.
# 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