Is_prime. What am I doing wrong?


I have looked through the code many times and the logic seems to make sense, but this keeps popping up "Your function fails on is_prime(9). It returns True when it should return False."

What am I doing wrong?

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


Two problems exist in this line of code..

You forgot to put range before (2, x - 1)


In Python2.0
for an example..take range(2,6)
range(2,6)means a list -- >[2,3,4,5] ,It already excludes 6 (so last digit of range function is excluded).
so no need to subtract 1 from x?


That is correct. I've gone on the assumption that was the implication of the author, in a literal sense.


Thank you, it worked!


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