-
-
Save wasafiri/785fab5e2ec887f65fe4 to your computer and use it in GitHub Desktop.
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
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