Could someone help me streamline this? Like eliminate unnecessary coding and etc?
I got the script to work, although I couldn't figure out how to handle small prime numbers such as 2 and 3. It wouldn't output "this number is prime" (see script below) so I had to force prime detection. Also, 6 = 3 + 3, and 4 = 2 + 2, but it wouldn't output that either, instead it would just return to the python prompt, so I forced those two.
Thanks!
import math
def main():
def calcPrime(squareI2t,n):
if n == 2 or n == 3: # couldnt figure out how to handle these small
isEvenAndPrime(n)# primes, so I forced prime detection
elif n == 4 or n == 6:
print "="*52,"\nFound two prime numbers that sum to",n,"!"
print n, "=",n/2,"+",n/2,"\n","="*52
else:
for x in range(2, squareIt + 1):
if n % x == 0:
break
if x == squareIt:
isEvenAndPrime(n)
def isEvenAndPrime(n):
print "="*52,"\nERROR:",n,"is already prime."
def isPrime(p):
if p == 2:
return True
else:
result = primeTest(p)
return result
return False
def isEven(num):
if n %2 == 0:
return True # is even
else:
print "="*52,"\nERROR:",n,"is not even. Please use only even numbers.\n"
return False
def primeTest(p):
stop = int(math.ceil(math.sqrt(p/2)))+1
for i in range(3, stop, 2):
#print "testing", i, p, p%i
if p % i == 0:
return False
return True # is a prime
n = int(raw_input('Enter number to test: '))
squareIt = int(math.sqrt(n))
calcPrime(squareIt,n)
if isEven(n):
found = 0
for p in range(3, n/2, 2):
#print "testing", p, n-p
if isPrime(p) and isPrime(n-p):
print "="*52,"\nFound two prime numbers that sum to",n,"!"
print n, '= %d + %d' % (p, n-p),"\n","="*52
found = 1
break
if __name__ == '__main__':
main()