# is_prime: why doesn't it work?

#1

my code looks like this

``````def is_prime(x):
if x<2:
return False
else:
i=2
while i<=x:
i=i+1
m=x/i
if isinstance(m, int):
return False
break
else:
return True``````

i know that this is not the most elegant version, but i't like to understand why it isnt working. It fails already for x=2. If i wrote what i think i did, for the case x=3, m=x/i should be 3/4, which is not an integer. So why is my function returning False for is_prime(3)?

#2

Take a look at this post. Also, 1, 2, 3 are all prime your code returns False on 1 and 2

#3

Thanks! That is one nice solution i see that my idea would involve unnecessary calculations. But i still don't get why my version doesn't work even for the first couple of numbers
Codeacademy wants 1 to not be a prime, that's why i defined it that way. I also don't understand why it doesn't work for x=2. In that case, by the time the isinstance function is called, m should be 2/3, shouldn't it?

#4

Once you hit this it will return false if it is an int.

#5

but m=2/3 isn't an int right? i must be missing a really simple thing, im sorry.

#6

If it is an int it returns False else it returns True, so if it is a fraction it returns true.

#7

Right, so why am i getting a False?

#8

Example:

``````def is_prime(x):
if x<2:
return False
else:
i=2
while i<=x:
i=i+1
m=x/i
print(i, m)
if isinstance(m, int):
return False
break
else:
return True``````

You might notice what is going on then.