Skip to content

Instantly share code, notes, and snippets.

@EderRoger
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EderRoger/a3a784a7cd0f94f8e79d to your computer and use it in GitHub Desktop.
Save EderRoger/a3a784a7cd0f94f8e79d to your computer and use it in GitHub Desktop.
Ruby Conjectura de Collatz
class Conjectura
attr_reader :elements
def initialize
@elements = Hash.new
end
def calc(range)
range.each{ |i| calc_seq_cache i }
end
def calc_seq_cache(n)
@elements[n] = calc_seq(n,1)
end
def calc_seq(n,s)
if @elements[n]
return @elements[n] + s -1
elsif n == 1
return s
elsif n & 1 == 0
return calc_seq(n/2,s+1)
else
return calc_seq(3*n+1,s+1)
end
end
end
require 'spec_helper'
require 'benchmark'
describe Conjectura do
it 'do calc 999.999 get hightest sequence' do
conjectura = Conjectura.new
Benchmark.bm do |x|
x.report { conjectura.calc(1..999_999) }
end
expect(conjectura.elements.values.max).to eq(525)
end
end
require_relative '../lib/conjectura'
require 'yaml'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment