Skip to content

Instantly share code, notes, and snippets.

@ihercowitz
Created January 5, 2012 11:33
Show Gist options
  • Save ihercowitz/1564897 to your computer and use it in GitHub Desktop.
Save ihercowitz/1564897 to your computer and use it in GitHub Desktop.
import sys
def prime(number):
n = abs(number)
if n < 1:
return False
if n==2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
if __name__=="__main__":
if len(sys.argv[1:]) == 0:
print "usage: pyPrime.py <number>"
sys.exit(0)
try:
value = int(sys.argv[1])
except:
print "The parameter must be a number"
print "usage: pyPrime.py <number>"
sys.exit(0)
if value < 0:
print "The parameter must be a positive number"
print "usage: pyPrime.py <number>"
sys.exit(0)
if value % 2 != 0:
print "This validations works only for Even numbers"
print "usage: pyPrime.py <number>"
sys.exit(0)
primes=[x for x in range(3, value, 2) if prime(x)]
expressions=[]
while len(primes) > 0:
rest = value - primes[::-1][0]
if rest in primes:
expressions.append("%s + %s" %(primes[::-1][0], rest))
primes.remove(rest)
primes.pop()
print "Goldbach's conjecture"
print "%s = %s" %(value, ", ".join(expressions))
@ihercowitz
Copy link
Author

Goldbach's conjecture is one of the oldest unsolved problems in number theory and in all of mathematics. It states:

Every even integer greater than 2 can be expressed as the sum of two primes.[1]

The number of ways an even number can be represented as the sum of two primes[2]

A Goldbach number is a number that can be expressed as the sum of two odd primes. Therefore, another statement of Goldbach's conjecture is that all even integers greater than 4 are Goldbach numbers.

The expression of a given even number as a sum of two primes is called a Goldbach partition of the number. For example,

  4 = 2 + 2
  6 = 3 + 3
  8 = 3 + 5
 10 = 7 + 3 or 5 + 5
 12 = 5 + 7
 14 = 3 + 11 or 7 + 7

Usage: python pyGoldbach.py

Ex:
$ python pyPrime.py 100
Goldbach's conjecture
100 = 97 - 3, 89 - 11, 83 - 17, 71 - 29, 59 - 41, 53 - 47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment