Skip to content

Instantly share code, notes, and snippets.

@kcburge
Created September 1, 2016 20:36
Show Gist options
  • Save kcburge/2962c7865fce3ad132baecc69fdd0c12 to your computer and use it in GitHub Desktop.
Save kcburge/2962c7865fce3ad132baecc69fdd0c12 to your computer and use it in GitHub Desktop.
class Collatz
def initialize(observer)
@observer = observer
@lengths = Hash.new
end
def length(num)
len = @lengths[num]
if !len
if num == 1
len = 1
else
len = 1 + length((num % 2 == 0) ? (num/2) : (num * 3) + 1)
end
@lengths[num] = len
# notify the observer we calculated a length
@observer.notify(num, len)
end
len
end
end # Collatz
class Longest
attr_reader :number, :length
def initialize(max)
@max = max
@number = 0
@length = 0
end
def notify(num, len)
if num <= @max && len > @length
@number = num
@length = len
end
end
end
max = 999999
start_time = Time.now
longest = Longest.new(max)
collatz = Collatz.new(longest)
2.upto(max) do |num|
collatz.length(num)
end
puts "Number with longest chain is #{longest.number()}"
puts "Length of longest chain is #{longest.length()}"
puts "Time taken #{Time.now - start_time}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment