Skip to content

Instantly share code, notes, and snippets.

@cefaijustin
Created May 12, 2018 20:25
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 cefaijustin/f31a540ef5a5d9230788f2802c401d04 to your computer and use it in GitHub Desktop.
Save cefaijustin/f31a540ef5a5d9230788f2802c401d04 to your computer and use it in GitHub Desktop.
Longest Collatz Sequence with comments.
# n → n/2 (n is even)
# n → 3n + 1 (n is odd)
# Write a method to determine a number's collatz sequence.
# Find the number (1 to 1,000,000) with the longest sequence.
# collatz method defined below with (n) as an argument.
def collatz(n)
# longest_sequence will serve as an empty array to
# store the longest collatz sequence.
longest_sequence = []
# next, we loop through each number (1 through 1,000,000).
# sequence = [x] <-- this means that for 1, 2, 3, and so on
# each number '[x]' will be run through the loop, and the resulting
# collatz values of that number will be pushed into the
# sequence array, UNTIL the sequence ends at 1.
(1..n).each do |x|
sequence = [x]
until sequence.last === 1
if sequence.last.even?
sequence.push(sequence.last / 2)
else
sequence.push(sequence.last * 3 + 1)
end
end # <-- until statement ends here.
# now we check to see how long the sequence is.
# if it's longer than the previous sequence,
# this block will push it into the
# 'longest_sequence' array.
if sequence.length > longest_sequence.length
longest_sequence = sequence
end
end
# then, we print the values of the longest sequence.
p "#{longest_sequence[0]} produces the longest Collatz sequence, with a length of #{longest_sequence.length}!"
end
# last, we call the method with an argument of 1,000,000
# which is the max number required for the lesson.
collatz(1000000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment