每日一程-14.python-打印冰雹序列

Author: Notus([email protected])
Create: 2019-02-21
Update: 2019-02-21

给定一个正整数,打印出对应的冰雹序列

冰雹序列

冰雹序列是由Collatz猜想提出的。

给出下列公式和初始的正整数值,生成的序列以1结束。

公式如下:

* 如果数字是偶数,除以2
* 如果数字是奇数,乘以3,再加上1
* 当数等于1时,退出程序

从初始数字开始应用公式,然后在生成的每个数字上反复应用公式,得到整个序列。

环境

Python version: 3.7.1

代码如下(a.py)

'''
    给定一个正整数,打印出冰雹序列。
    @Author: Notus([email protected])
    @Create: 2019-02-21
    @Update: 2019-02-21
    @Version: 0.1
'''

theNum = input("请输入一个正整数:")

while not theNum.isdigit() or int(theNum) <= 0:
    print("请输入一个合法的正整数!")
    theNum = input("请输入一个正整数:")
    
theNum = int(theNum)
print(theNum)
count = 1
while theNum > 1:
    if theNum % 2 == 0:
        theNum //= 2
    else:
        theNum = theNum * 3 + 1
    print(theNum)
    count += 1
else:
    print("此序列长为: {}".format(count))

运行

C:\Users\Notus\Desktop>python a.py
请输入一个正整数:10
10
5
16
8
4
2
1
此序列长为: 7

猜你喜欢

转载自www.cnblogs.com/leo1875/p/10415727.html