StayAheadOfLife
StayAheadOfLife

Reputation: 55

Function testing for primes not working as needed

It's supposed to find out if the given input is a prime number or not.

def is_prime(x):
    if x <= 1:
        return False
    elif x == 2 or x == 3:
        return True
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
            else:
                return True

But

is_prime(9)

gives True where it should return False.

I can't find the bug, need help.

Upvotes: 0

Views: 35

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122122

You return True the moment you find a factor that doesn't divide x evenly. 2 doesn't divide 9 so you return True then:

>>> x = 9
>>> n = 2
>>> if x % n == 0:
...     print False
... else:
...     print True
... 
True

You need only return True when you determined that no factors exist, so outside your loop:

for n in range(2, x-1):
    if x % n == 0:
        return False
return True

You don't need to test up to x - 1, testing up to int(x ** 0.5) + 1 is enough (so up to the square root):

def is_prime(x):
    if x <= 1:
        return False
    if x in (2, 3):
        return True
    for n in range(2, int(x ** 0.5) + 1):
        if x % n == 0:
            return False
    return True

Upvotes: 2

Related Questions