【问题标题】:python slightly modified Collatz Conjecture programpython稍作修改的Collat​​z猜想程序
【发布时间】:2017-06-13 06:04:10
【问题描述】:

我被分配了一个任务来编写一个 Collat​​z 猜想程序,修改如下:

  1. 我们知道程序总是在偶数上除以 4,即使是不能被 4 整除的偶数,所以 6 之后的下一步将是 6/4 == 1。
  2. 我们知道即使有替代行为,程序也总是会达到停止条件,不确定代码中是否还有其他更改...

它需要

  1. 计算从 n 到我们到达停止条件的步数
  2. 返回 Shortz(n) 中所有步骤的总和,包括 n 本身

作为最终答案,我需要返回(737458374680773的所有步骤的总和)*(98325112的步骤数)

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

至于这个提示:

不确定代码是否还有其他变化...

我认为我不需要用奇数公式更改任何内容,因为在我看来这太牵强了(但是嘿,我知道的不多,请赐教:))。

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

这是我的代码:

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

非常感谢!

【问题讨论】:

    标签: python collatz


    【解决方案1】:

    您的逻辑错误处理“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。

    不确定代码是否还有其他变化...

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

    也许就像改变一样简单:

    while(num !=1):
    

    改为:

    while num > 1:
    

    这(以及使用//)允许您的两个示例编号都可以解析。

    【讨论】:

    • 很好的分析! (在我眼里:))我想可能是这样,但下周才会知道。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多