Skip to content

Instantly share code, notes, and snippets.

@bstolte
Created October 21, 2015 18:12
Show Gist options
  • Save bstolte/d7ab8ec2b90eec6bac13 to your computer and use it in GitHub Desktop.
Save bstolte/d7ab8ec2b90eec6bac13 to your computer and use it in GitHub Desktop.
Collatz Sequence - find longest chain of collatz values from 1 to 1,000,000
def collatz(n)
length = 1
loop do
if n == 1
return length
end
if n % 2 == 0
n = n / 2
else
n = (3*n) + 1
end
length += 1
end
end
longest = 0
longest_n = nil
(1..1000000).each do |n|
length = collatz(n)
if length > longest
longest = length
longest_n = n
end
end
puts longest
puts longest_n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment