Author: Notus(hehe_xiao@qq.com)
Create: 2019-02-21
Update: 2019-02-21

冰雹序列

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

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

公式如下:

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

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

环境

Python version: 3.7.1

代码如下(a.py)

'''
	给定一个正整数,打印出冰雹序列。
	@Author: Notus(hehe_xiao@qq.com)
	@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

相关文章:

  • 2022-12-23
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
  • 2021-08-06
  • 2022-02-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-04-26
  • 2021-12-22
  • 2022-12-23
  • 2021-11-05
  • 2021-07-28
相关资源
相似解决方案