Last active
August 9, 2021 11:39
-
-
Save alecthegeek/12a60f4b952d70703344f2e78bf544c3 to your computer and use it in GitHub Desktop.
Calculate the Collatz series -- see https://youtu.be/5mFpVDpKX70
This file contains hidden or 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
#!/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