Is_prime


#1

In the exercise given in the title of is_prime I tried to follow the instruction and get the result right. However I didn't understand the code for the loop. Can someone explain it to me why we needed to limit the rage from 2 and x-1. In particular this part of the code

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


def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2,x-1):
            if x % n == 0:
                return False
        else:
            return True
    
x = raw_input("Is prime number?")
print is_prime(int(x))



Thanks you, that would be a great help.


#2

well -1 is not necessary, range does not include the stop value

you need to check that x is not divisible by all number between 2 (2 included) and x (x not included), this is the condition for being a prime number, to achieve this we use a loop


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.