-
Notifications
You must be signed in to change notification settings - Fork 0
/
collatz_Sequence.py
40 lines (31 loc) · 1.19 KB
/
collatz_Sequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""Collatz Sequence, by Al Sweigart [email protected]
Generates numbers for the Collatz sequence, given a starting number.
More info at: https://en.wilkipedia.org/wiki/collatz_comjecture
View this code at https://nostarch.com/big-book-small-python-projects
Tags: tiny, beginner, math"""
import sys, time
print('''Collatz Sequence, or, the #n +1 problem
By Al Sweigart [email protected]
The Collatz sequence is a sequence of numbers produced from a starting
number n, following three rules:
1) If n is even, the next number n is n / 2.
2) If n is odd, the next number n is n * 3 + 1.
3) 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.
''')
print('Enter a starting number (greater than 0) or QUIT:')
response = input('> ')
if not response.isdecimal() or response == '0':
print('You must enter an interger greater than 0.')
sys.exit()
n = int(response)
print(n, end='', flush=True)
while n != 1:
if n % 2 == 0: #if n is even ...
n = n // 2
else: # Otherwise, n is odd...
n = 3 * n + 1
print(', ' + str(n), end='', flush=True)
time.sleep(0.1)
print()