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

Collatz步数计算代码bug修复及批量遍历功能实现咨询

问题根因

你现有代码的问题是直接在Collatz归约循环中修改了存储用户输入值的变量n,循环执行结束后n已经被迭代更新为1,因此打印时无法输出原始输入的数值。

修复代码(包含遍历需求)

将步数计算封装为独立函数,避免修改原始数值,同时实现从输入最大值到1的全量遍历打印:

def calc_collatz_steps(num):
    steps = 0
    # 使用临时变量参与计算,不修改原始传入值
    temp = num
    while temp > 1:
        steps += 1
        if temp % 2 == 0:
            temp = temp // 2
        else:
            temp = temp * 3 + 1
    return steps

max_val = int(input('n? '))
# 倒序遍历从输入值到1的所有整数
for current in range(max_val, 0, -1):
    steps = calc_collatz_steps(current)
    print(f"{current} takes {steps} steps")

单值计算修复版本(无遍历)

如果你暂时不需要遍历功能,仅修复原始输入值输出错误,可直接修改原有代码如下:

n = int(input('n? '))
# 提前保存原始输入值
original_n = n
n_steps = 0

while n > 1:
        n_steps+=1
        if n % 2 == 0:
                n = n // 2
        else:
                n = n * 3 + 1
        
print(f"{original_n} takes {n_steps} steps")

内容的提问来源于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:48:03