euler/euler014.rb

24 lines
453 B
Ruby

def collatz(num)
list = []
current_num = num
while current_num > 1
list << current_num
if current_num % 2 == 0
current_num /= 2
else
current_num = 3*current_num + 1
end
end
list << 1
end
def longest_chain(num)
chain_length = {}
(1..num).each do |starting_num|
chain_length[starting_num] = collatz(starting_num).count
end
chain_length.sort_by { |key, value| value }.last
end
puts longest_chain(999999)