Skip to content

Instantly share code, notes, and snippets.

@TonyArra
Created July 26, 2018 19:34
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 TonyArra/1a6ac62d2e9ebeca51e2658bc0d8ff62 to your computer and use it in GitHub Desktop.
Save TonyArra/1a6ac62d2e9ebeca51e2658bc0d8ff62 to your computer and use it in GitHub Desktop.
#!/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