This will be much faster. It does fewer prime checks and does not check numbers that are even for prime.
**With GMPY2:**
$ time python3 goldbach.py 12345678912345678
This is a test of Goldbach's Conjecture that for all even integers
greater than 2 there are two primes that add up to that even number.
61 + 12,345,678,912,345,617 = 12,345,678,912,345,678
real 0m0.027s
user 0m0.018s
sys 0m0.009s
**With my Home Grown IsPrime:**
$ time python3 goldbach.py 12345678912345678
This is a test of Goldbach's Conjecture that for all even integers
greater than 2 there are two primes that add up to that even number.
61 + 12,345,678,912,345,617 = 12,345,678,912,345,678
real 0m2.405s
user 0m2.405s
sys 0m0.000s
**Listing:**
# Goldbach's Conjecture tester.
from gmpy2 import is_prime
import sys
# or use home grown IsPrime
def IsPrime(n):
if (n == 2 or n == 3):
return True
if (n <= 1 or n % 2 == 0 or n % 3 == 0):
return False
for i in range(5, int(n**.5)+1, 6):
if (n % i == 0 or n % (i + 2) == 0):
return False
return True
def goldbach(numb):
if numb == 4:
return 2,2 # the only time we use 2
else:
for p in range(3, numb, 2): # just check odds after 2
if is_prime(p) and is_prime(numb-p):
return p,numb-p
raise Exception(f"Found a counter-example to the Goldbach conjecture: {numb}")
if len(sys.argv) > 1:
N = int(sys.argv[1])
else:
N = 1
print("This is a test of Goldbach's Conjecture that for all even integers")
print("greater than 2 there are two primes that add up to that even number.\n")
while (N < 3 or N%2):
N = int(input("Please enter an even number > 3 to check with Goldbach's Conjecture> "))
p1,p2 = goldbach(N)
print(f"{p1:,} + {p2:,} = {N:,}")