Skip to content

Instantly share code, notes, and snippets.

@wasafiri
Created February 2, 2014 04:46
Show Gist options
  • Save wasafiri/785fab5e2ec887f65fe4 to your computer and use it in GitHub Desktop.
Save wasafiri/785fab5e2ec887f65fe4 to your computer and use it in GitHub Desktop.
collatz
def collatz_calculate n
if n.even?
return n/2 #if n is even, divide it by 2
elsif n.odd?
return (3 * n) + 1 #if n is odd, multiply it by 3 and add 1
end
end
def collatz n
collatz_array = [n]
until collatz.array.last == 1 #until the last number in the array is 1, loop
collatz_array << collatz_calculate(collatz.array.last)
end
puts collatz_array #by now the last number should be 1
end
collatz 13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment