Skip to content

Instantly share code, notes, and snippets.

@trishume
Created July 6, 2011 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save trishume/1068502 to your computer and use it in GitHub Desktop.
Save trishume/1068502 to your computer and use it in GitHub Desktop.
Collatz conjecture chains in ruby
# 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