Skip to content

Instantly share code, notes, and snippets.

@thiagoa
Last active July 13, 2017 19:26
Show Gist options
  • Save thiagoa/b82ec7a30f355e6e3d4828ab4e7795ea to your computer and use it in GitHub Desktop.
Save thiagoa/b82ec7a30f355e6e3d4828ab4e7795ea to your computer and use it in GitHub Desktop.
ZERO = Int64.new(0)
ONE = Int64.new(1)
TWO = Int64.new(2)
THREE = Int64.new(3)
ONE_MILLION = Int64.new(1_000_000)
class Collatz
def initialize(min : Int64, max : Int64)
@min = min
@max = max
@cache = Array(Int64).new(@max, ZERO)
end
def longest_length
n = @min
max_n, max_length = ZERO, ZERO
while true
break if n == @max
length = length_for(n)
if length > max_length
max_n, max_length = n, length
end
n += 1
end
[max_n, max_length]
end
private def length_for(n : Int64)
@cache[n - ONE] = next_for(n)
end
private def next_for(n : Int64)
return ONE if n == ONE
return @cache[n - ONE] if n <= ONE_MILLION && @cache[n - ONE] != ZERO
if n % TWO == ZERO
ONE + next_for(n / TWO)
else
ONE + next_for(n * THREE + ONE)
end
end
end
collatz = Collatz.new(ONE, ONE_MILLION)
max_n, max_length = collatz.longest_length
puts "N that generates biggest length: #{max_n}"
puts "Biggest length: #{max_length}"
@rafaelrpbelo
Copy link

Why do you not put ZERO, ONE, TWO, THREE, ONE_MILLION inside Collatz class?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment