Skip to content

28678: 角谷猜想

http://cs101.openjudge.cn/practice/28678/

所谓角谷猜想,是指对于任意一个正整数,如果是奇数,则乘3加1,如果是偶数,则除以 2,得到的结果再按照上述规则重复处理,最终总能够得到1。如,假定初始整数为5,计算过程分别为16、 8、4 、 2 、 1。

程序要求输入一个整数,将经过处理得到 1的过程输出来。

输入

一个正整数 n。(n ≤ 2,000,000)

输出

从输入整数到 1 的步骤,每一步为一行,每一部中描述计算过程。最后一行输出 "End"。如果输入为 1,直接输出 "End"。

请保证输出的数字不带小数点。

样例输入

sample1 input:
5

sample1 output:
5*3+1=16
16/2=8
8/2=4
4/2=2
2/2=1
End

样例输出

sample2 input:
1

sample2 output:
End

提示

tags: 循环结构

来源

2024 TA-wjl, https://www.luogu.com.cn/problem/B2077

与21459一样。

python
def collatz_sequence(n):
    if n == 1:
        print("End")
        return

    while n != 1:
        if n % 2 == 1:
            next_n = 3 * n + 1
            print(f"{n}*3+1={next_n}")
        else:
            next_n = n // 2
            print(f"{n}/2={next_n}")
        n = next_n

    print("End")

# Sample input
n = int(input())

# Calculate and print the result
collatz_sequence(n)

递归

python
def cal(a):
    if a % 2 == 0:
        s = int(a/2)
        print(f'{a}/2={s}')
    else:
        s = int(a*3+1)
        print(f'{a}*3+1={s}')
    if s == 1:
        print('End')
        return
    cal(s)

cal(int(input()))