这段代码怎么会找到质数,is_prime(9) returns True?

How come in this code to find prime numbers, is_prime(9) returns True?

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 而不是 False.

不太明白

range (2,9) 包括此列表:2,3,4,5,6,7,8

9 % 3 == 0, 那么为什么我没有得到 False 作为该函数的答案?

这是因为您实际上并没有循环,因为您在第一个循环中 return 为真(9 % 2 == 0 为假)。

像这样应该可以解决问题:

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

您可以通过保留原始循环而不提前退出来大大简化逻辑。您可以将第一个条件添加到最终 return:

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

  return x > 2

顺便说一句,Erastothenes 筛法是一种以更好的 运行 时间复杂度解决此问题的非常酷的方法。这里有一个link来简单解释一下:

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