Python: How to implement 3x+1 problem with python?

1. Problem description

Insert picture description here

2.code

x = int(input('请输出一个正整数:'))
#x = int(x)
n = 0
xlist = list()
xlist.append(x)
while x != 1:
    if x % 2 == 0:
        x = x / 2
        n = n + 1
        xlist.append(x)
    else:
        x = 3 * x + 1
        n = n + 1
        xlist.append(x)
print(f"经过 {n} 次运算得到结果,运算序列为 {xlist}")

Guess you like

Origin blog.csdn.net/qq_40797015/article/details/112177843