Skip to content

Instantly share code, notes, and snippets.

@lapointexavier
Last active August 29, 2015 14:11
Show Gist options
  • Save lapointexavier/594863f8a0a83ac9c363 to your computer and use it in GitHub Desktop.
Save lapointexavier/594863f8a0a83ac9c363 to your computer and use it in GitHub Desktop.
Collatz Conjecture
import random
num_steps = 0
def collatz(term):
"""Recursively compute the Collatz conjecture for a Natural number
http://en.wikipedia.org/wiki/Collatz_conjecture
term:
A natural number > 1
"""
global num_steps
num_steps = num_steps + 1
print('{0}: {1}'.format(num_steps, term))
if term == 1:
return 1
elif term % 2 == 0:
return collatz(term / 2)
else:
return collatz((term * 3) + 1)
if __name__ == '__main__':
collatz(random.randint(1, 987654321))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment