0

As the title suggests I am working on finding all the pairs of prime numbers that satisfy the goldbachs conjecture for any given number n. This is my implementation of the algorithm:

import math
def prime(n):
    for i in range(2,int(math.sqrt(n))+1):
        if n%i==0:
            return False
    return True
def Plist(n):
    res=[]
    for i in range(2,n+1):
        if prime(i):
            res.append(i)
    return res
def Goldbach(n):
    res=[]
    plist=Plist(n)
    hmap={}
    for num in plist:
        diff=n-num
        if diff in plist and (num not in hmap.keys()):
             res.append((num,diff))
             hmap[num]=1
             
       
    return res
    

This algorithm is giving me redundant pairs and I want to know how to get rid of one redundant pair, Example (3,23) and (23,3)

  • 1
    The `num not in hmap.keys()` check is not necessary, since you look at each number just once. Instead you should check that `num <= diff` to get rid of the redundant pairs. – tobias_k Sep 16 '22 at 11:24

1 Answers1

0
import math
def prime(n):
    for i in range(2,int(math.sqrt(n))+1):
        if n%i==0:
            return False
    return True
def Plist(n):
    res=[]

    for i in range(2,n+1):
        if prime(i):
            res.append(i)
    return res
def Goldbach(n):
    plist=Plist(n)
    res=[]
    while plist:
        i = plist.pop()
        for j in plist:
            p = (i,j)
            if sum(p)==n:
                res.append(p)
    return res
         

print(Goldbach(26))
islam abdelmoumen
  • 662
  • 1
  • 3
  • 9