I want to know the number of ways that a given positive even number can be written as the sum of two primes.
At the moment, I have this code:
n = int(input(">"))
def genprimes(n):#generate primes from 2 to n
primes = []
for i in range(2,n):
prime = True
for a in range(2,i):
if i % a == 0:
prime = False
if prime == True:
primes.append(i)
return primes
pairs = []
primes = genprimes(n)
for prime1 in primes:
for prime2 in primes:
if prime1 + prime2 == n and [prime1,prime2] not in pairs and [prime2,prime1] not in pairs:
pairs.append([prime1,prime2])
print(len(pairs))
It works, but it becomes a little slow when n
goes above 10,000
ish. Can anyone think of a more efficient way to find this value, so that it yields quick results for high values?
You have two slow algorithms.
To get your list of primes, you separately check each number for prime-hood. The fastest way get a list of primes is to use a pre-built list of primes--that is what I do for such problems. The list of primes up to 2**16 (65,536) takes only 6542 integers and I store that list in a module. You may prefer to use the Sieve of Eratosthenes which is generally recognized as the fastest way to get such a list from scratch.
You then try each pair of primes to see if they add to your target number. It would be much faster to, for each prime p
, see if n-p
is also prime. You could check n-p
with a binary search, as @Shubham suggests, but it would probably be faster to have two indices, one regularly going up and yielding p
and the other going down as needed checking for n-p
. It might be quickest to copy your prime list to a set and use that to check if n-p
is in the list. These last two techniques are of order n
, but for numbers only up to 10,000 the overhead may affect which technique is best. And yes, for such problems 10,000 is not very large. Finally, if memory is not a concern, @BoulderKeith points out that you could leave the prime list as a list of Booleans (True/False) and very quickly check if n-p
is prime--this is the fastest, if most memory-consuming, technique of all.