|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Recommended: Python 3.6+ |
| 4 | + |
| 5 | +""" |
| 6 | +Collatz Conjecture - Python |
| 7 | +
|
| 8 | +The Collatz conjecture, also known as the |
| 9 | +3x + 1 problem, is a mathematical conjecture |
| 10 | +concerning a certain sequence. This sequence |
| 11 | +operates on any input number in such a way |
| 12 | +hat the output will always reach 1. |
| 13 | +
|
| 14 | +The Collatz conjecture is most famous for |
| 15 | +harboring one of the unsolved problems in |
| 16 | +mathematics: does the Collatz sequence really |
| 17 | +reach 1 for all positive integers? |
| 18 | +
|
| 19 | +This program takes any input integer |
| 20 | +and performs a Collatz sequence on them. |
| 21 | +The expected behavior is that any number |
| 22 | +inputted will always reach a 4-2-1 loop. |
| 23 | +
|
| 24 | +Do note that Python is limited in terms of |
| 25 | +number size, so any enormous numbers may be |
| 26 | +interpreted as infinity, and therefore |
| 27 | +incalculable, by Python. This limitation |
| 28 | +was only observed in CPython, so other |
| 29 | +implementations may or may not differ. |
| 30 | +
|
| 31 | +11/24/2021 |
| 32 | +David Costell (DontEatThemCookies on GitHub) |
| 33 | +""" |
| 34 | + |
| 35 | +import math |
| 36 | + |
| 37 | +print("Collatz Conjecture") |
| 38 | +number = input('Enter a number to calculate: ') |
| 39 | +try: |
| 40 | + number = float(number) |
| 41 | +except: |
| 42 | + print('Error: Could not convert to integer.') |
| 43 | + print('Only integers/floats can be entered as input.') |
| 44 | + input() |
| 45 | + exit() |
| 46 | + |
| 47 | +# Checks to see if input is valid |
| 48 | +if number == 0: |
| 49 | + input('Error: Zero is not calculable. ') |
| 50 | + exit() |
| 51 | +if number < 0: |
| 52 | + input('Error: Negative numbers are not calculable. ') |
| 53 | + exit() |
| 54 | +if number == math.inf: |
| 55 | + input('Error: Infinity is not calculable.') |
| 56 | + exit() |
| 57 | + |
| 58 | +print('Number is', number) |
| 59 | +input('Press ENTER to begin.') |
| 60 | +print('BEGIN COLLATZ SEQUENCE') |
| 61 | + |
| 62 | +def modulo(): |
| 63 | + global number |
| 64 | + modulo = number % 2 # Modulo the number by 2 |
| 65 | + if modulo == 0: # If the result is 0, |
| 66 | + number = number / 2 # divide it by 2 |
| 67 | + else: # Otherwise, |
| 68 | + number = number * 3 + 1 # multiply by 3 and add 1 |
| 69 | + |
| 70 | +def final(): |
| 71 | + print('END COLLATZ SEQUENCE') |
| 72 | + print('Sequence has reached a 4-2-1 loop.') |
| 73 | + input() |
| 74 | + exit() |
| 75 | + |
| 76 | +while True: |
| 77 | + # Execute the sequence |
| 78 | + modulo() |
| 79 | + print(number) |
| 80 | + if number == 1.0: |
| 81 | + break |
| 82 | + |
| 83 | +final() |
0 commit comments