Created
November 21, 2016 06:30
-
-
Save ryanveroniwooff/8a17d73be64c7b76eb69c3dae73aab2a to your computer and use it in GitHub Desktop.
This file contains 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
#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