python 稍微修改了 Collat​​z Conjecture 程序

python slightly modified Collatz Conjecture program

我接到了一个编写 Collat​​z 猜想程序的作业,修改如下:

  1. We know the program ALWAYS divides by 4 on even numbers, even ones not divisible by 4, so the next step after 6 would be 6/4 == 1.
  2. We know the program always reached a stop condition even with the alternative behavior, not sure if there was another change in the code...

它需要

  1. count the number of steps from n until we reach a stop condition
  2. return the sum of all the steps in Shortz(n) including n itself

作为最终答案,我需要return(737458374680773的所有步数之和)*(98325112的步数)

问题是当我计算这个:737458374680773 它进入无限循环。

至于这个提示:

not sure if there was another change in the code...

我不认为我需要用奇数公式改变任何东西,因为在我看来它太牵强了(但嘿,我知道的不多,启发我:))。

关于我的代码有什么问题或我没有得到有关作业的任何想法?

这是我的代码:

import math
def shortz(num):
    iterations = 0
    stepsSum = 0
    while( math.isnan(num) or num<0):
        num = int(input("Please supply a non-negative number ==>  "))
        print("")
    while(num !=1):
         if (num%2==0):
             num /= 4 
             stepsSum += num       
             print (str(iterations+1) + ") " + str(num))
         else:
             num = (num*3) -1
             print (str(iterations+1) + ") "+ str(num))
         iterations += 1 
         stepsSum += num
    print ("the number of iterations is " + str(iterations))
    print ("the sum of all steps is " + str(stepsSum))

q=0
while (q<1):
    x = int(input("Input positive number: "))
    shortz(x)
    z = str(input("Again?")).lower()
    if z[0]=='n':
        q=2

非常感谢!

您的逻辑错误处理“2”并进入无限循环:

2/4 是 0.5 -> (0.5 * 3) - 1 -> 0.5 -> (0.5 * 3) - 1 -> 0.5 等

Input positive number: 2
1) 0.5
2) 0.5
3) 0.5
4) 0.5
5) 0.5
6) 0.5
7) 0.5
...

您可能需要使用 num //= 4 而不是 num /= 4 来去掉小数部分。但这并不能解决这个问题,只是将重复结果从 0.5 更改为 0。

not sure if there was another change in the code...

可能是指如何处理零。它不是正整数,因此不是 shortz() 的有效输入,但它仍然作为内部结果出现(如果您使用 //),因此必须进行特殊处理。 (如果您继续使用 /,则为 0.5)

也许像改变一样简单:

while(num !=1):

改为:

while num > 1:

这(连同使用 //)可以让您的示例数字得到解析。