Created
October 21, 2015 18:12
-
-
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
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
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