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

print is_prime(9) returns True instead of False.

I don't quite understand.

The range (2,9) includes this list: 2,3,4,5,6,7,8

and 9 % 3 == 0, So how come I do not get False as the answer of that function?

martineau
  • 119,623
  • 25
  • 170
  • 301
FNM
  • 59
  • 4
  • 3
    The `else: return True` should have one level of indent less (yes, you read that right). Also you should run the loop from `range(2, int(x ** .5))` – cs95 Nov 11 '18 at 01:09
  • Because your loop only executes once, for 9 % 2. – Tieson T. Nov 11 '18 at 01:11

2 Answers2

1

This is because you don't actually loop, as you return True during the first cycle (9 % 2 == 0 is False).

Something like this should solve the problem:

def is_prime(x):
  if x < 2:
    return False
  for n in range(2, x):
    if x % n == 0:
      return False
  return True
mistiru
  • 2,996
  • 3
  • 11
  • 27
1

You can simplify the logic a good amount by keeping your original loop and not exiting early. You can add your first conditional to your final return:

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

  return x > 2

BTW, the Sieve of Erastothenes is a pretty cool method of solving this problem in a much better run time complexity. Here's a link to a brief explanation:

https://math.stackexchange.com/questions/58799/why-in-sieve-of-erastothenes-of-n-number-you-need-to-check-and-cross-out-numbe

LeKhan9
  • 1,300
  • 1
  • 5
  • 15
  • With this code, negative numbers, 0 and 1 will be considered as prime whereas they aren't – mistiru Nov 11 '18 at 01:18
  • Great point, I made the terrible assumption the caller would take that into consideration. Added a fix. – LeKhan9 Nov 11 '18 at 01:26