Skip to content

Instantly share code, notes, and snippets.

@AnthonyBloomer
Last active August 20, 2016 17:33
Show Gist options
  • Save AnthonyBloomer/444cc481a57491b6f4a9309a0e3ee3c9 to your computer and use it in GitHub Desktop.
Save AnthonyBloomer/444cc481a57491b6f4a9309a0e3ee3c9 to your computer and use it in GitHub Desktop.
Collatz conjecture
import sys
# Take any positive integer n.
# If n is even, divide it by 2 to get n / 2.
# If n is odd, multiply it by 3 and add 1 to obtain 3n + 1.
# The conjecture is that no matter what number you start with, you will always eventually reach 1.
def collatz(n):
if n % 2 == 0:
return n / 2
else:
return ((n * 3) + 1) / 2
if __name__ == '__main__':
n = int(sys.argv[1])
if n < 0:
sys.exit('N should be a positive integer.')
count = 0
while n != 1:
print(n)
n = collatz(n)
count += 1
print('Operation took ' + str(count) + ' steps.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment