Skip to content

Instantly share code, notes, and snippets.

@mdnestor
Last active January 3, 2023 12:15
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 mdnestor/573662dea80e7089da4f4d4938f25743 to your computer and use it in GitHub Desktop.
Save mdnestor/573662dea80e7089da4f4d4938f25743 to your computer and use it in GitHub Desktop.
Collatz function
def collatz(n: int) -> int:
return n // 2 if n % 2 == 0 else 3*n + 1
def height(n: int) -> int:
# The Collatz height of an integer is the # of steps to return to 1
h = 0
while n > 1:
n = collatz(n)
h += 1
return h
def height_r(n: int) -> int:
# Recursive implementation of Collatz height
return 1 + height_r(collatz(n)) if n > 1 else 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment