1

I've tried to write a code for the weak Goldbach Conjecture, which states that every odd number greater than 5 can be expressed as the sum of three prime numbers. However, the code only returns (0, 0, 0). I only need one triple that works rather than a list of triples. Any ideas where I'm going wrong? Also I know that the code isn't the most efficient as it is, especially using the eratosthenes function to generate my primes, but this is the form that I've been asked to code in.

def eratosthenes(n):
    primes = list (range(2, n+1))
    for i in primes:
        j=2
        while i*j<= primes[-1]:
            if i*j in primes:
                primes.remove(i*j)
            j=j+1
    return primes

def weak_goldbach(N):
    x, y, z = 0, 0, 0
    result = 0
    if not N % 2:
        prime = eratosthenes(N)
        while result != N:
            for i in range(len(prime)):
                x = prime[i]
                if result == N: 
                    break
                for j in range(i, len(prime)):
                    y = prime[j]
                    result = x + y
                    if result == N: 
                        break 
                    for k in range (j, len(prime)):
                        z = prime[k]
                        result = x + y + z
                        if result == N:break
    return x, y, z
4

1 回答 1

2

错误

您的代码存在一些问题,但第一个问题以及它失败的原因是not N % 2总是对奇数计算为假,跳过循环并返回您设置的初始值 x、y 和 z。

它也存在逻辑问题;当 x+y+z == N 时,您的代码在最内部的循环中中断,然后在正确设置结果时外部循环中断,但仅在更改 x 或 y 之后!这意味着即使您解决了第一个问题,您的代码也总是会返回错误的结果。

效率低下

首先,您根本不需要复杂的中断逻辑!当您第一次发现它的总和为N时,您可以返回x, y, z

其次,您不需要在中间循环中使用 result=x+y 代码,因为它与弱哥德巴赫猜想无关,而且无论如何都不正确。

第三,外部的while循环完全没用。它什么都不做,除了如果内部循环由于某种原因没有找到结果,则创建一个无限循环。

其他问题

最好减少嵌套;因此,确保它是大于 5 的奇数的条件应该是负数,如果不成立,应该返回异常。这样,函数的主体就不会嵌套在条件中,这使得它更具可读性。

更正的代码有效

def weak_goldbach(N):
     x, y, z = 0, 0, 0
     result = 0
     if not N % 2 or N < 7:
         raise Exception("Bad input - must be odd number greater than 5.")
     prime = eratosthenes(N)
     for i in range(len(prime)):
         x = prime[i]
         for j in range(i, len(prime)):
             y = prime[j]
             for k in range (j, len(prime)):
                 z = prime[k]
                 if x+y+z == N:
                     return x, y, z
     raise Exception("Looks like %d is the exception to the weak Goldbach conjecture!" % N)
于 2018-12-17T15:06:02.317 回答