15.6 is_prime


The code runs perfectly fine, and returns True for a prime number. Even then the control gives error message that for (-7) it is returning True instead of False. As (-7) is prime it should be returning True, which is correct according to me, but then why that error message.

Replace this line with your code. 
def is_prime(x):

    if (x<=1):
        return False
    elif (x==2):
        return True
        while(n <= x-1):
            if (x%n == 0):
                return False
            n += 1
        if c>1:
            return False
            return True
print is_prime(57)

if x < 2:

pretty much covers both those lines. Since it returns, we won't need an elif.

We only need this check if we are iterating only odd numbers. For a minimal logic brute force approach, such as devised in this exercise we only need to check for greater than 2.

if x > 2:
    # loop code that returns False, or not
return True



I understood the fact later that we are only concerned with the numbers greater than 2 and this is why (-7) was not regarded as a prime number with its abs(-7)=7.

I have now modified the code accordingly and looks fine now.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.