Skip to content

Instantly share code, notes, and snippets.

@chrisedgemon
Forked from bkonkle/collatz.py
Created April 28, 2010 19:09
Show Gist options
  • Select an option

  • Save chrisedgemon/382568 to your computer and use it in GitHub Desktop.

Select an option

Save chrisedgemon/382568 to your computer and use it in GitHub Desktop.
Collatz Conjecture
import random
def collatz(n):
"""
Run the collatz conjecture for integer n
http://en.wikipedia.org/wiki/Collatz_conjecture
"""
step = lambda m: m * 3 + 1 if m % 2 else m / 2
i = 0
while n != 1:
print n
n = step(n)
return i
def main():
start = random.randint(0, 100000)
steps = collatz(start)
print "The number %i was converged to 1 in %i steps." % (start, steps)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment