Created
July 6, 2011 22:26
-
-
Save trishume/1068502 to your computer and use it in GitHub Desktop.
Collatz conjecture chains in ruby
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
# small recursive version | |
def collatzr(num,arr = []) | |
return arr if arr.unshift(num)[0] == 1 | |
num.even? ? collatzr(num / 2,arr) : collatzr(num * 3 + 1,arr) | |
end | |
# pretty looping version | |
def collatz(num,arr = []) | |
while num != 1 | |
arr << num | |
num = num.even? ? num / 2 : num * 3 + 1 | |
end | |
arr.push(1) | |
end | |
#example | |
puts collatz(7) | |
puts "----" | |
puts collatzr(15) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment