Pythonallenge中的“3n + 1”编程挑战

时间:2017-10-11 00:49:09

标签: python

我是Python的初学者。我正在尝试解决UVa Online Judge上的3n + 1问题。该程序与输入文件一起工作正常。但是,我提交了几次但仍然遇到运行时错误。

import sys
def compute(i, j):
    maxCycleLength = 1
    if i <= j/2:
        k = j/2+1
    else:
        k = i

    for n in range(k, j+1):
        num = n
        cycleLength = 1
        while (num != 1):
            if num%2 != 0:
                num = 3*num+1
            else:
                num = num/2
            cycleLength += 1
        if cycleLength > maxCycleLength:
            maxCycleLength = cycleLength

    return maxCycleLength

while True:
    nums = sorted(int(x) for x in next(sys.stdin).split())
    m = compute(nums[0], nums[1])
    print("{} {} {}\n".format(nums[0], nums[1], m))

0 个答案:

没有答案