Created
May 3, 2012 09:51
-
-
Save antimon2/2584785 to your computer and use it in GitHub Desktop.
Integer#collatz
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
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