Skip to content

Instantly share code, notes, and snippets.

@alecthegeek
Last active August 9, 2021 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alecthegeek/12a60f4b952d70703344f2e78bf544c3 to your computer and use it in GitHub Desktop.
Save alecthegeek/12a60f4b952d70703344f2e78bf544c3 to your computer and use it in GitHub Desktop.
Calculate the Collatz series -- see https://youtu.be/5mFpVDpKX70
#!/usr/bin/env python3
def collatz(n: int, p = True):
i: int = 0
while n > 1:
if n % 2 != 0:
n = 3*n +1
i += 1
if p: print(f"{i}: {n}")
n //= 2
i += 1
if p: print(f"{i}: {n}")
return(i)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("n", help="run the 3n+1 function on n", type=int)
parser.add_argument("-p", "--print", help="print all the intermediate steps", action="store_true")
args = parser.parse_args()
print(f"{collatz(args.n, args.print)} steps for collatz({args.n:,})")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment