Collatz Sequence
The Collatz sequence, also called the 3n + 1 problem, is the simplest impossible math problem. (But don’t worry, the program itself is easy enough for beginners.) From a starting number, n, follow three rules to get the next number in the sequence:
If n is even, the next number n is n / 2.
If n is odd, the next number n is n * 3 + 1.
If n is 1, stop. Otherwise, repeat.
It is generally thought, but so far not mathematically proven, that every starting number eventually terminates at 1. More information about the Collatz sequence can be found at https://en.wikipedia.org/wiki/Collatz_conjecture.
collatz_sequence.py
1"""Collatz Sequence, by Al Sweigart al@inventwithpython.com
2Generates numbers for the Collatz sequence, given a starting number.
3More info at: https://en.wikipedia.org/wiki/Collatz_conjecture
4This code is available at https://nostarch.com/big-book-small-python-programming
5Tags: tiny, beginner, math"""
6
7import sys, time
8
9print('''Collatz Sequence, or, the 3n + 1 Problem
10By Al Sweigart al@inventwithpython.com
11
12The Collatz sequence is a sequence of numbers produced from a starting
13number n, following three rules:
14
151) If n is even, the next number n is n / 2.
162) If n is odd, the next number n is n * 3 + 1.
173) If n is 1, stop. Otherwise, repeat.
18
19It is generally thought, but so far not mathematically proven, that
20every starting number eventually terminates at 1.
21''')
22
23print('Enter a starting number (greater than 0) or QUIT:')
24response = input('> ')
25
26if not response.isdecimal() or response == '0':
27 print('You must enter an integer greater than 0.')
28 sys.exit()
29
30n = int(response)
31print(n, end='', flush=True)
32while n != 1:
33 if n % 2 == 0: # If n is even...
34 n = n // 2
35 else: # Otherwise, n is odd...
36 n = 3 * n + 1
37
38 print(', ' + str(n), end='', flush=True)
39 time.sleep(0.1)
40print()