Created
July 26, 2018 19:34
-
-
Save TonyArra/1a6ac62d2e9ebeca51e2658bc0d8ff62 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env ruby | |
def longest_collatz(n) | |
longest_sequence = 0 | |
longest_n = 0 | |
collatz_map = {} | |
until n == 1 | |
n -= 1 | |
if collatz_map.key? n | |
length = collatz_map[n] | |
else | |
length = collatz(n) | |
collatz_map[n] = length | |
end | |
if length > longest_sequence | |
longest_sequence = length | |
longest_n = n | |
end | |
end | |
longest_n | |
end | |
def collatz(n) | |
length = 1 | |
until n == 1 | |
length += 1 | |
n = n.even? ? (n / 2) : (3 * n + 1) | |
end | |
length | |
end | |
puts longest_collatz(ARGV[0].to_i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment