Created
January 5, 2012 11:33
-
-
Save ihercowitz/1564897 to your computer and use it in GitHub Desktop.
Goldbach's conjecture - http://en.wikipedia.org/wiki/Goldbach%27s_conjecture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Goldbach's conjecture is one of the oldest unsolved problems in number theory and in all of mathematics. It states:
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,
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