Is_prime: failing on 9


#1



For some reason it keeps failing on 9...


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


#2

a function ends the moment a return keyword is reached

so for x=9, the first number tested by the loop is 2, so:

if 9 % 2 == 0

which is false, so else runs, True is returned, the function ends

but for a number to a prime number, x (9 in this case) shouldn't be divisible by any number in range 2 till x (9 in this case), so True should be returned after the loop

if the number is not a prime number, return False will end the function at some point during the loop


#3

why it fails on 9 ??
suppose x is 9..
when you loop over it...
n is looping on range(2,8) which is a list... [2,3,4,5,6,7]
at first loop n takes value of 2 and as 9 is not divisible by 2, The test x % n == 0 turns out to be False and else code executes and it returns True but It had to return False

To fix this issue, you need to fix the else part, (with respect to your current code) such that It does not return True and only return True when all if tests has done.

Try using for/else?


#4

for/else worked. thanks so much!


#5

range() does not include its stop value, so if you change x-1 to x, you can get rid of:

    elif x == 2 or x == 3:
        return True
    else:

given you for loop can handle all that. for x=2, the loop condition will be false, so else will run and True will be returned


#6

you understood why your program had this bug ( fails at 9) now ? :slight_smile:


#7

It's really helpful. The problem has bothered me for quite a while. for/else solved it !


#9

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