Is_prime


#1



This is the error i get:
Oops, try again. Your function fails on is_prime(4). It returns True when it should return False.

I'm not sure why this is not returning correctly as 4/2 = 2 which should return as type 'int'.
What am i missing?


def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        for n in range(2, (x-1)):
            if type(x/n) == 'int':
                return False
    return True


#2

Also, I got this to work by replacing if type(x/n) == 'int' with

if x % n == 0

but I don't understand why my original code doesn't function correctly


#3

You started well here

But you dont need an elif statement f you write your for loop like this

        for n in range (2,x):
`#Loops from 2 to x which will be your prime number

#Checks if your number is not odd.
if (x % n) == 0:
return False
#If it is it will return true after the for loops iteration
return True

So put it all together.
You get

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

#4

Thanks for the quick reply @bandit ! That makes more sense now. I got the uses of / in python 2 and 3 mixed up in my head too. After I thought about it some more.

In python 2 (5/2) = 2 but (5.0/2.0) = 2.5 (code academy appears to be in python 2)
In python 3 (which I learned first) 5/2 = 2.5

not sure if this will help anyone else but it helped me.


#5

Haha it is quite relevant to any one doing the excercise. :slight_smile:


#6

This was very helpful. My code was very similar, though I tried using an if/else statement in the for loop like this:

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

When running the above code, the function fails on is_prime(2). Can someone help me understand why this does not work?


#7

Hi everyone,

This seems to have worked for me:

def is_prime(x):

if x < 2:   # Integers less than 2 are not prime
    return False

else:
    for n in range(2, x): # Iterate through all integers up until the number
       if x % n == 0: # Check to see if number is divisible by anything besides itself
        return False
    else:
        return True

I had to add the "if x < 2: return False" statement before it worked properly.