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

旧街凉风 提交于 2019-12-20 03:59:06

问题


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?


回答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



回答2:


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



来源:https://stackoverflow.com/questions/53244958/how-come-in-this-code-to-find-prime-numbers-is-prime9-returns-true

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