Skip to content

Instantly share code, notes, and snippets.

@ilyakrasnov
Created March 14, 2017 21:00
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 ilyakrasnov/62f229fd74c0a8e4a7dc9021c1ca33d2 to your computer and use it in GitHub Desktop.
Save ilyakrasnov/62f229fd74c0a8e4a7dc9021c1ca33d2 to your computer and use it in GitHub Desktop.
class Collatz
def initialize(n)
@current_number = n
@sequence = []
end
def compute_next_collatz
@sequence << @current_number
if @current_number == 1
return @sequence
elsif @current_number % 2 == 0
@current_number = @current_number / 2
compute_next_collatz
else
@current_number = @current_number * 3 + 1
compute_next_collatz
end
end
end
def longest_collatz(n)
longest_sequence = { number: 0, length: 0 }
1.upto(n) do |ceiling|
sequence = Collatz.new(ceiling).compute_next_collatz
# ceiling 1 -> sequence: [1]
# compare to current longest_sequence:
# longest_sequence = { number: 1, length: 1 }
#
# ceiling 2 -> sequence: [2, 1]
# compare to current longest_sequence:
# longest_sequence = { number: 2, length: 2 }
#
# ceiling 3 -> sequence: [3, 10, 5, 16, 8, 4, 2, 1]
# compare to current longest_sequence:
# longest_sequence = { number: 3, length: 8 }
#
# code to write
end
puts "The longest collatz sequence from 1 to #{n} is the sequence for the number #{longest_sequence[:number]} and has the length of #{longest_sequence[:length]}"
end
longest_collatz(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment