Skip to content

Instantly share code, notes, and snippets.

@bil-bas
Forked from syntacticsugar/14_collatz_sequence.rb
Last active December 17, 2015 17:19
Show Gist options
  • Save bil-bas/5644889 to your computer and use it in GitHub Desktop.
Save bil-bas/5644889 to your computer and use it in GitHub Desktop.
module Collatz
class << self
attr_reader :lengths
def length_recursive(current, counter=0)
counter += 1
if current == 1
counter
elsif @lengths.key? current
@lengths[current] + counter # Take advantage of already working out the length from this number.
else
next_num = current.even? ? current / 2 : current * 3 + 1
length_recursive next_num, counter
end
end
private :length_recursive
def length(initial)
@lengths ||= Hash.new {|h, k| h[k] = length_recursive k }
@lengths[initial]
end
def longest(range)
range.max_by {|n| length n }
end
end
end
puts "Answer is #{Collatz.length 13}"
t = Time.now
puts "Longest sequence starts with #{Collatz.longest 1...1_000_000}"
puts "Took %.2fs" % (Time.now - t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment