哥德巴赫 Python 输出

Goldbach Python Output

我为哥德巴赫猜想做了一个python代码。 问题是我的输出看起来像这样

Enter the lower limit: 8
Enter the Upper limit: 10
8 = 3 + 5
10 = 3 + 7
10 = 5 + 5

我希望我的输出看起来像

8 = 3 + 5
10 = 3 + 7 = 5 + 5

有什么办法可以这样格式化吗?

我只发布 for 循环:

for n in range (lo_limit, up_limit + 1): #lo_limit and up_limit is what you input
  if (n % 2 == 0):
    for a in range (1, n + 1): 
      if is_prime(a): #is_prime represent numbers that are prime
        for b in range(1, n + 1):
          if is_prime(b):
            if (a + b == n):
              if (a <= b):
                print(n, "=", a, "+", b)

主要()

试试这个:

for n in range (lo_limit, up_limit + 1):
    if (int(n) % 2 == 0):
        printedstring=str(n)
        for a in range (1, n + 1): 
            if is_prime(a):
                for b in range(1, n + 1):
                    if is_prime(b):
                        if (a + b == n):
                            if (a <= b):
                                printedstring = printedstring + str(" = ", a, " + ", b)
        print(printedstring)

您的函数可以通过一些简单的更改得到简化和加速:

def goldbach(lo, hi):
    # 1. just step by 2 instead of checking for even numbers
    for n in range(lo, hi + 1, 2):
        # 2. keep a list of found matches instead of building up a string 
        matches = [str(n)] 
        # 3. for any 'a', you can just subtract to find 'b' instead of looping
        # 4. instead of testing for a <= b, just run the 'a' loop halfway
        for a in range(1, n // 2 + 1):
            if is_prime(a) and is_prime(n-a):
                matches.append('{} + {}'.format(a, n-a))
        # 5. join up the matches and print at the end
        print(' = '.join(matches))

为了更简洁,整个内部 for 循环也可以表示为列表理解。

您可以轻松地进一步优化它,方法是事先生成您范围内的素数列表,然后迭代这些素数并检查补码的成员资格,而不是重复进行素数测试。