得到错误的输出 (Ramanujan)

Getting the wrong output (Ramanujan)

基本上我想要函数做的是:

  1. 取一个整数输入并将其保存为n
  2. 打印包含两个条目的向量列表 (a,b),其中 a^3+b^3=n

例如,当我输入n = 443889时,我应该得到[(76,17),(38,73)]的输出,因为这个问题只有两个解决方案:46^3+17^3=44388938^3+73^3=443889 ]

但是使用我的代码,当我给出输入 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)

对复杂结果的检查略有不同,如果 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=443889

的结果

你可以早点停止循环;如果 a(n/2)**(1/3) 左右,您只需将 ab 互换即可得到结果;这可能看起来像(没有仔细检查边缘情况......):

from math import ceil

def ramanujans(n):

    res = []

    limit = ceil(((n/2)**(1/3)))

    for a in range(1, limit+1):
        s = n - a**3
        b = round(s**(1/3))
        result = a**3 + b**3
        if result == n:
            if a <= b:  # this is to cover the edge cases...
                res.append((a, b))
    return res

print(ramanujans(n=443889))  # [(17, 76), (38, 73)]
print(ramanujans(n=2000))    # [(10, 10)]
print(ramanujans(n=1729))    # [(1, 12), (9, 10)]

并且只会 return 'half' 结果。