You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环嵌套while循环逐次打印每次迭代对应数字的归1步数

考拉兹序列步数批量计算解决方案

你可以把单个数的归1步数计算逻辑封装为独立函数,在外层加for循环遍历1到你输入的最大值区间的所有数字即可,调整后代码如下:

# 封装单个数的归1步数计算函数
def count_collatz_steps(num):
    steps = 0
    n = num
    while n > 1:
        steps += 1
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
    return steps

max_num = int(input('n? '))
# 从最大值倒序遍历到1,匹配输入2先输出2再输出1的示例要求
for current_num in range(max_num, 0, -1):
    step_count = count_collatz_steps(current_num)
    print(f"{current_num} takes {step_count} steps")

改动说明

  • 将原代码的单次计算逻辑抽成count_collatz_steps函数,接收数字作为入参,返回对应的归1步数
  • 新增外层for循环,用range(max_num, 0, -1)实现从输入的最大值倒序遍历到1,符合给出的输出顺序要求
  • 用f-string简化了字符串拼接逻辑,可读性更高

内容的提问来源于stack exchange,提问作者user16545663

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:54:07