2015-09-23 22 views
1

我爲哥德巴赫猜想做了一個python代碼。 的事情是我的輸出看起來像這樣哥德巴赫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) 

的main()

+3

顯示您的代碼。 – tzaman

+2

這是非常難以回答,沒有任何代碼的工作。請考慮添加一個[MCVE](http://stackoverflow.com/help/mcve),或者至少您現在的代碼。 –

+1

是的,有一種方式,但不是沒有看到您的代碼,創建輸出 –

回答

0

試試這個:

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) 
+0

這不適合我,但它確實有幫助。 我printedstring = printedstring + STR( '=')+ STR(A)+ STR( '+')+ STR( 'B')。謝謝! –

+0

我應該開始測試我的東西......反正,很樂意幫助! –

1

你的功能可以簡化並加快了一噸了一些簡單的修改:

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)) 

爲了更簡潔,整個循環內部也可以表示爲列表理解。

你可以很容易地在你的範圍內生成素數的名單事先進一步優化這個,然後就遍歷這些和檢查成員的互補,而不是做重複素性測試。

相關問題