得到错误的输出(Ramanujan)

时间:2017-04-22 12:34:56

标签: python-3.x math output equation

基本上我想要的功能是:

  1. 获取整数输入并将其另存为n
  2. 打印包含两个条目(a,b)的向量列表,其中a^3+b^3=n
  3. 例如,当我输入n = 443889时,我应该得到[(76,17),(38,73)]的输出,因为此问题的唯一两个解决方案是:46^3+17^3=44388938^3+73^3=443889 < / p>

    但是在我的代码中,当我给出输入n=443889时,我得到输出[(76, 17), (75, 28), (74, 34), (73, 38), (72, 41)],即使这些向量中的一些没有给出我方程的解。

    def ramanujans(n):
        lista = []
        counter = 0
    
        for a in range(1,n):
            b = (n- (a**3))**(1/3)
            result = a**3 + b**3
    
            if isinstance(b,complex):
                break
            elif result == n:
                b = int(round(b))
                lista.insert(0,(a, b))
    
        return (lista)
    

1 个答案:

答案 0 :(得分:1)

对复杂结果进行一些不同的检查,并检查<div style="float:left;display:inline-block;"> <img src="http://localhost/test1/wp-content/uploads/2017/04/GautengNew-1.gif"; alt="" width="500" height="538" /> </div> <div style="float:left;display:inline-block;"> <table style="margin-left: 10%; float: left;" border="1" width="440"> <tbody> <!-- Table Rows Here --> </tbody> </table> </div> (仅整数比较),我似乎得到了正确的结果:

result == n

使用:

def ramanujans(n):
    res = []

    for a in range(1, n):
        s = n - a**3
        if s < 0:
            break
        b = round(s**(1/3))
        result = a**3 + b**3

        if result == n:
            res.append((a, b))

    return res

作为[(17, 76), (38, 73), (73, 38), (76, 17)]

的结果

你可以提前停止循环;如果n=443889a左右,您只需获得(n/2)**(1/3)a互换的结果;这可能看起来像(没有仔细检查边缘情况......):

b

只会返回半个&#39;结果。

相关问题