Skip to content

Instantly share code, notes, and snippets.

@barrysmyth
Created April 18, 2022 09:14
Show Gist options
  • Save barrysmyth/a2437e6403370bdd7489dc509238c5e2 to your computer and use it in GitHub Desktop.
Save barrysmyth/a2437e6403370bdd7489dc509238c5e2 to your computer and use it in GitHub Desktop.
Creating Collatz sequences/orbits from an integer.
def collatz(n):
"""The Collatz operator: If n is even return n/2 else return 3n+1."""
# If n is even then divide by 2.
if n%2==0:
return int(n/2)
# Otherwise return 3n+1
else:
return (3*n)+1
def collatz_orbit(n):
"""Calculate the sequence of integers by repeatedly applying the Collatz
operator until the result is 1. Return the resulting sequence."""
# Initialise the orbit (sequence of numbers).
orbit = []
# Loop until n=1.
while n>1:
# Add n to the orbit.
orbit.append(n)
# Apply the collatz rule to get a new n
n = collatz(n)
# Return the orbit with the root (1).
return orbit+[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment