Last active
July 13, 2017 19:26
-
-
Save thiagoa/b82ec7a30f355e6e3d4828ab4e7795ea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why do you not put ZERO, ONE, TWO, THREE, ONE_MILLION inside Collatz class?