is_prime not working


#1

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


#2

You should check if x is less than 2.

You have these backwards, change the not equal to equal, than flip the return statements.


#3

def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
var = True
for n in range(2,x-1):
if x % n != 0:
var = True
else:
var = False
# must break if one instance of even divisibility
break
return var

I'm no expert at Python, but i realized after messing with it for a while that since we are using a loop, even if there is an event in which the number is evenly divisible by another number other than 1 and itself, the loop will just continue resulting in an incorrect result. I found that using the break function when the loop comes across such an instance takes care of that issue.


#4

def is_prime(x):
if x <= 1:
return False
elif x <=3:
return True
elif x % 2 == 0 or x % 3 == 0:
return False
i = 5
while i * i <= x:
if x % i == 0 or x % (i+2) == 0:
return False
i=i+6
return True


#5

@stryk9_85
I think you are confused, you don't need to break as the function automatically ends when you use the return keyword.


#6

def is_prime(x):
if x < 2:
return False
else:
y = 0
for n in range(1,x+1):
if x % n == 0:
y += 1
if y == 2:
return True
else:
return False

this is my code. i tried it the other way. instead of checking if it is divisible by a certain number. i checked how many numbers are divisible to it. if its only 2 (1 and itself) then it is prime.