Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@juandesant
Last active August 4, 2021 16:24
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 juandesant/f6524331474ce46e0160ebea51640c51 to your computer and use it in GitHub Desktop.
Save juandesant/f6524331474ce46e0160ebea51640c51 to your computer and use it in GitHub Desktop.
Python implementation of the Collatz series as a generator
def next_collatz(n):
if n%2 == 0:
return n//2
else:
return 3*n+1
def collatz(n):
yield n
result = next_collatz(n)
while result != 1 and result :
yield result
result = next_collatz(result)
# when we arrive here, the final result is 1
yield 1
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment