Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#generates a collatz sequence for input n
def generate_sequence(n)
seq = [n]
while (n != 1) do
n.even? ? n /= 2 : n = (3 * n + 1)
seq << n
end
return seq
end
#finds number with the longest collatz sequence between 1 and 1 million
def find_longest_sequence
highest_length = 0
number = 0
i = 1
while (i < 1000000) do
new_length = generate_sequence(i).length
if (new_length > highest_length)
highest_length = new_length
number = i
i+=1
else
i+=1
end
end
puts "The number with the longest collatz sequence is: #{number} with a length of #{highest_length}."
end
find_longest_sequence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment