Is_prime "returns true when it should return false" problem


#1
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
      else:
        return True

i’m now getting Your function fails on is_prime(9). It returns True when it should return False. and I really have no idea what I’m doing wrong now.

Any help please?


#2

There should not be an else: return True clause. This is what is giving the false positives. Finish with a return True after the loop.


#3

Alright, I appreciate that, but can I get an explanation on how that works?

If the function just ends with “return True” wouldn’t it always return true? Or am I fundamentally misunderstanding something?


#5

Yes if none of the other return paths were followed.

less than two

greater than two

two

Those are the criteria with their own returns. Consider when x is 2. What happens with this range…

for n in range(2, x):

n_range[-1] is going to be 1 and the loop will not run. The fall through will be return True since 2 has just gone down that path.

Any value that is not divisible will also fall through the loop and return likewise, True.

Consider now when x is 3. The loop does run, but only through one iteration and then falls through to return True.

4 is immediately divisible, as is any even number so they get rejected on the first iteration. Only odd numbers will trigger more iterations, 3 notwithstanding.

Brute force means very few conditions. The above strategy has very few.

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

#7

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