Python Collatz Conjecture

The Collatz Conjecture is an unsolved problem in Mathematics which lends itself nicely to exploration with Python.

The idea is simple:

Pick a positive whole number. If it’s odd, multiply it by 3 and add 1. If it’s even, divide it by 2. Now you have a new number. Apply the same rules to the new number. What happens as you keep repeating the process?

Try a few examples manually, and then have a go at completing the program below to explore the conjecture with Python.

Details: Complete the function named collatz(). It has one parameter named number. It should return number // 2 if number is even and 3 * number + 1 otherwise. Hint: You can use the modulo operator to check for evenness.

def collatz(number):
    pass


n = int(input("Enter a positive whole number: "))
print(n)
while n != 1:
    n = collatz(n)
    print(n)

Once you’ve had a good try, you may want to look at my solution:

You might think that the number you start with affects the number you end up with. Perhaps some numbers eventually reach 1, while others go off to infinity. Collatz conjectured that if you start with a positive whole number and run this process long enough, all starting values will lead to 1.

Over the years, many mathematicians have been drawn Collatz conjecture. They have tested billions of examples without finding a single exception to Collatz’s prediction. However, it is not yet proven that ALL positive whole numbers will eventually reach 1.

The Collatz Conjecture with a Negative Starting Number

You may be curious as to what happens if we apply the Collatz formulas to a negative initial number. Have a play with this idea now if it interests you. You can easily use the same program as above to explore this – maybe changing the input message to encourage negative input…

Generally speaking, if we apply the Collatz function on any integer, then it is conjectured that it ends up in one of five “cycles”:

  • …→0→0→0→…
  • …→1→4→2→1→…
  • …→−1→−2→−1→…
  • …→−5→−14→−7→−20→−10→−5→…
    …→−17→−50→−25→−74→−37→−110→−55→−164→−82→−41→−122→−61→−182→−91→−272→−136→−68→−34→−17→…

This article has explored the Collatz Conjecture with Python. I hope you found it interesting. Happy computing!

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Join our mailing list

Join our mailing list to receive awesome articles about learning Python and Computer Science in a fun and accessible way, straight to your inbox.