python - Function testing for primes not working as needed -
it's supposed find out if given input prime number or not.
def is_prime(x): if x <= 1: return false elif x == 2 or x == 3: return true else: n in range(2, x-1): if x % n == 0: return false else: return true
but
is_prime(9)
gives true
should return false
.
i can't find bug, need help.
you return true
moment find factor doesn't divide x
evenly. 2
doesn't divide 9
return true
then:
>>> x = 9 >>> n = 2 >>> if x % n == 0: ... print false ... else: ... print true ... true
you need return true
when determined no factors exist, outside loop:
for n in range(2, x-1): if x % n == 0: return false return true
you don't need test x - 1
, testing int(x ** 0.5) + 1
enough (so square root):
def is_prime(x): if x <= 1: return false if x in (2, 3): return true n in range(2, int(x ** 0.5) + 1): if x % n == 0: return false return true
Comments
Post a Comment