Skip to content

Instantly share code, notes, and snippets.

@amcaplan
Last active August 29, 2015 14:00
Show Gist options
  • Save amcaplan/11356768 to your computer and use it in GitHub Desktop.
Save amcaplan/11356768 to your computer and use it in GitHub Desktop.
Collatz Conjecture (aka Project Euler Problem 14) using Benchmark library - don't copy, the point is to solve it yourself!
require 'benchmark'
class Collatz
@@collatzes = {1 => 1}
def self.max_chain_starter_under(highest)
(1...highest).max_by { |option| Collatz.new(option).length }
end
def initialize(num)
@num = num
end
def length
collatz(@num)
end
def collatz(num)
@@collatzes[num] ||= 1 + (num.even? ? collatz(num/2) : collatz(num*3 + 1))
end
private :collatz
end
benchmark_results = Benchmark.measure do
puts Collatz.max_chain_starter_under(1_000_000)
end
benchmark_results2 = Benchmark.measure do
puts Collatz.max_chain_starter_under(1_000_000)
end
puts "First time running: #{benchmark_results}"
puts "Second time running: #{benchmark_results2}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment