Skip to content

Instantly share code, notes, and snippets.

@antimon2
Created May 3, 2012 09:51
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 antimon2/2584785 to your computer and use it in GitHub Desktop.
Save antimon2/2584785 to your computer and use it in GitHub Desktop.
Integer#collatz
class Integer
def collatz &block
return to_enum :collatz unless block_given?
return self if self < 0
block[self]
n = self
until n < 2
n = n.even? ? n/2 : n*3+1 # <- *1
block[n]
end
self
end
end
# 3.collatz.to_a
# => [3, 10, 5, 16, 8, 4, 2, 1]
# 27.collatz.count
# => 112
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment