柯拉茨序列,也称为3n + 1问题,是最简单的不可能数学问题。(不过不用担心,程序本身对初学者来说已经足够简单了。)从一个起始数字,n,遵循三个规则得到序列中的下一个数字:
- 如果
n是偶数,那么下一个数字n就是n / 2。 - 如果
n是奇数,那么下一个数n就是n * 3 + 1。 - 如果
n为 1,则停止。否则,重复。
一般认为,但迄今为止没有数学证明,每个起始数最终终止于 1。关于柯拉茨序列的更多信息可以在en.wikipedia.org/wiki/Collatz_conjecture找到。
当您运行collatz.py时,输出将如下所示:
Collatz Sequence, or, the 3n + 1 Problem
By Al Sweigart email@protected
The Collatz sequence is a sequence of numbers produced from a starting
number n, following three rules:
`--snip--`
Enter a starting number (greater than 0) or QUIT:
> 26
26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
Collatz Sequence, or, the 3n + 1 Problem
By Al Sweigart email@protected
`--snip--`
Enter a starting number (greater than 0) or QUIT:
> 27
27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1模数运算符可以帮助您确定一个数字是偶数还是奇数。记住这个操作符是一种“余数”操作符。23 除以 7 是 3 余 2,而23 mod 7只是 2。偶数除以 2 没有余数,奇数除以 2 有余数 1。当n为偶数时,第 33 行if n % 2 == 0:中的条件求值为True。当n为奇数时,计算结果为False。
"""Collatz Sequence, by Al Sweigart email@protected
Generates numbers for the Collatz sequence, given a starting number.
More info at: https://en.wikipedia.org/wiki/Collatz_conjecture
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, beginner, math"""
import sys, time
print('''Collatz Sequence, or, the 3n + 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 integer 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() 试着找出下列问题的答案。尝试对代码进行一些修改,然后重新运行程序,看看这些修改有什么影响。
- 以 32 开头的柯拉茨序列中有多少个数字?
- 以 33 开头的柯拉茨序列中有多少个数字?
- 起始数为 2 的幂(2、4、8、16、32、64、128 等等)的排序序列是否总是只由偶数组成(除了最后的 1)?
- 输入
0作为起始整数会发生什么?
