I have a question about a script i'm making. It asks the user to input an integer, then finds two prime numbers that sum up to the number, and displays what those two prime numbers are ( something like "54 = 5 + 49" ). I have most of the code working, but i'm not sure how to finish it up. So far, it finds the prime numbers that make up the number, but when it encounters a number that doesnt sum up to two prime numbers the program exits and goes back to the prompt with no message of any kind.

Primarily, what i'd like to do is create a check to see if the number the user entered is even. IF the number is even, the program then finds the two prime numbers that sum to that number. If it is NOT even, the program should exit with a "Number not even" message or similar.

Heres my code so far, can someone provide some input?

def main():
    import math
    def is_prime(p):
        prime = True
        if p%2 == 0:
            prime = False
        else:
            for i in range(3, math.ceil(math.sqrt(p/2)), 2):
                if p % i == 0:
                    prime = False
                    break
            return prime
    n = int(raw_input('Ener number to test: '))

    for p in range(3, n/2, 2):
        if is_prime(p) and is_prime(n-p):
            print n, '= %d + %d' % (p, n-p)
            print "Found two prime numbers that sum to",n
            break      

main()

Thanks!

Recommended Answers

All 7 Replies

"return prime" is not indented correctly. For the "print a message if the number isn't even" you already test for even with
if n % 2 == 0: ## even
.
else: ## not even
#do what you want here for numbers that aren't even

Note that 5 is not even but has two primes, 2 and 3 that add up to 5. Same for 7 (2+5). There are probably more. I have the flu so you'll have to figure it out. Also WTF is main() there for? Eliminate def main() and the main() call at the bottom and you have the same program. Do you have to allow for more than one pair of prime numbers adding up to the input value. Hopefully not, as then you would have to store the results in a list.

Hi, and thanks. Hope you feel better soon. And no, I dont have to allow for more than one set of prime numbers. In fact, thats all i'm supposed to output, just one set of prime numbers.

I altered my code with your suggestions and get a somewhat more workable program, but it still isnt quite rite. I tried my best to code an error message for uneven input numbers, and it sort of works, but see the output below. Instead of displaying one message, it displayed several... why? And how can I get it to display just one? (I barely know what i'm doing here... but i'm trying hard to learn)

Heres my code as it is now:

import math
    def is_prime(p):
        prime = True
        if p%2 == 0:
            print n,"is not even. Please enter only even numbers."
            prime = False
        else:
            for i in range(3, math.ceil(math.sqrt(p/2)), 2):
                if p % i == 0:
                    prime = False
                    break
                    print n,"is not even. Please enter only even numbers."
                return prime
    n = int(raw_input('Enter number to test: '))

    for p in range(3, n/2, 2):
        if is_prime(p) and is_prime(n-p):
            print n, '= %d + %d' % (p, n-p)
            print "Found two prime numbers that sum to",n
            break

Here is the output:

Enter number to test: 62
62 = 25 + 37
Found two prime numbers that sum to 62

Enter number to test: 67
67 is not even. Please enter only even numbers.
67 is not even. Please enter only even numbers.
67 is not even. Please enter only even numbers.
67 is not even. Please enter only even numbers.


And how do I handle when an uneven number does add up to the sum of two prime numbers?

return prime is still incorrectly indented. Try the code below. When you can't figure something out, break it down into smaller, bite sized chunks. Test the first part and when you are satisfied that it works, test the second part, etc. I may have gone overboard with the functions here, but the principle is to get it into digestible chunks. I also added print statements for testing, to see what is going on.

import math

##---------------------------------------------------------------------
def is_prime(p):
##----------  first part
        if p == 2 :     ## why can't we have 2+3=5
            print "p == 2"
##  return out of the function here
            return True
##----------  second part
        else:
            result = test_for_prime(p)
##  return out of the function here
            return result 
#
##   you had "return prime" indented so it only executed with the "else" 
##   clause i.e. (p % 2 != 0).  We no longer use it since we return in
##   both the if() and else()
#
##   this is just a "safety".  We should never reach here
        return False

##---------------------------------------------------------------------
def test_for_even(num):
     if n %2 == 0:
          return True     ## is even
     else:
          print n,"is not even. Please enter only even numbers."
          return False

##---------------------------------------------------------------------
def test_for_prime(p):
##   you calculate sqrt(p/2) every time you cycle through
##   the for() loop.  Once is enough.  Also it has to be
##   an integer--I don't know what math.sqrt returns
     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 out of the function here
               return False
     return True     ## is a prime

##=====================================================================
n = int(raw_input('Enter number to test: '))
result = test_for_even(n)
if result:     ## "if test_for_even(n):" is a shorthand method
     found = 0
     for p in range(3, n/2, 2):
        print "testing", p, n-p  
        if is_prime(p) and is_prime(n-p):
            print n, '= %d + %d' % (p, n-p)
            print "Found two prime numbers that sum to",n
            found = 1
            break
     if not found :
          print "No prime number sums found for", n

Dude, your awesome. Thanks so much for your help!

I used the code you posted, but am still having a weird return on the error messages.

Here is the output below using your posted code:

Enter number to test: 63
63 is not even. Please enter only even numbers.
63 is not even. Please enter only even numbers.
63 is not even. Please enter only even numbers.

Enter number to test: 5
This should return a "not even" message.


Enter number to test: 71
71 is not even. Please enter only even numbers.
71 is not even. Please enter only even numbers.
71 is not even. Please enter only even numbers.
71 is not even. Please enter only even numbers.

Enter number to test: 49
>>>

I tried all odd numbers below 49, they all exit without the "not even" message. Every odd number above 49 gives one or more messages.

How do I get it to stop showing multiple "not even" messages? And how would I get numbers below 49 to return the same error message?

The code only gives one message on my computer so you'll have to post the code you are using. The problem has to be in a loop since you are getting more than one message. Are you calling the function "test_for_even()" after the "for p in range(3, n/2, 2):"? Also, do a search for "is not even". You might have it in more than one place.

Heres the code i'm using, it's the same code you posted earlier, just trying to figure out how to eliminate the multiple messages.

import math

def is_prime(p):
        if p == 2 :
            print "p == 2"
            return True
        else:
            result = test_for_prime(p)
            return result 
        return False

def test_for_even(num):
     if n %2 == 0:
          return True     ## is even
     else:
          print n,"is not even. Please enter only even numbers."
          return False

def test_for_prime(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: '))
result = test_for_even(n)
if result:
     found = 0
     for p in range(3, n/2, 2):
        print "testing", p, n-p  
        if is_prime(p) and is_prime(n-p):
            print n, '= %d + %d' % (p, n-p)
            print "Found two prime numbers that sum to",n
            found = 1
            break
     if not found :
          print "No prime number sums found for", n

Also, I found what was causing the multiple "not even" messages, although I cant explain it. I would press F5 to run the script, enter a number and get a good result. Well, then I ran "main()" from the same shell so I didnt have to keep switching back and fourth between the program and the shell. This is what caused the multiple messages for some reason...

If I run the script from the editor with F5, no problem. But once I start calling main() from the shell, thats when it start phreakin out...

Anyway, 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.

I'll post the script below, but could someone help me streamline it? Like eliminate unnecessary coding and etc?

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()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.