Question

Here is a code that determines whether an input is PRIME number or not.

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

But the if condition inside the for loop doesn't work as expected. If x < 2, it should return false. So is_prime(1) should return false as 1 is less than 2. But the program returns True instead, which is not expected. On the other hand, if you put that if just outside the for loop like this, IT WORKS:

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

Why is this happening?

Était-ce utile?

La solution

Over here,

for n in range(2, x - 1):

the for loop never runs if x == 1, then, you are essentially saying:

for n in range(2, 0):

which can't happen, so it just returns True from the else statement.

Your second function works because, as you said, the if statement is outside of the for loop

Autres conseils

def is_prime(x):
    if x < 9:
        return x in {2, 3, 5, 7}
    elif not (x % 2):
        # even
        return False
    else:
        upto = int(x ** 0.5)  # test to sqrt(x)
        # test divisibility by odd numbers
        return all(x % div for div in range(3, upto+1, 2))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top