# is_prime function

#1

[THIS HAS BEEN SOLVED - COULD NOT MARK THIS POST SOLVED OR DELETE IT (SORRY)]

Hi,

I was hoping to get some help with this function. I've written it out as:

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

When I run this in python it runs and returns the right answer after looping, but not until the end. How can I go about fixing this?

#2

Hi,

I don't understand what you want to fix, but your function returns True for x = 4.

The problem is here:

You need to check all numbers beginning with 2 not 3, but you only need to check integers that are smaller than sqrt(x).

#3

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

hi this is the right code for the assignment but I was confused on the else part . What does the for n in range(2,x) if x % n ==0 achieve? Specifically what is n in that block? thanks

#4

Hi @life1012016
n simply goes through the range that you created (2 to whatever x happens to be). Python automatically assigns variables so in this case it assumes you are looping through the integers in yr range. If n % x == 0 that means that there is no remainder meaning it is divisible, thus it is not a prime number, hence return false. If it manages to go through the whole loop without fulfilling the "if" statement, then no numbers were divisible, and it is a prime number (return True). Hope this helps!