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

和自甴很熟 提交于 2019-12-02 07:17:16

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!