简体   繁体   English

如何处理 Python 中素数检查的否定情况?

[英]How to handle negative cases for prime check in Python?

With regard to the "xrange" function - ("range" in Python3) what happens when I do a negative check inside a loop?关于“xrange”函数 - (Python3 中的“range”)当我在循环内进行否定检查时会发生什么? In this case, a negative number could be regarded as an edge case, but always returns None.在这种情况下,负数可被视为边缘情况,但始终返回 None。 Any insights?任何见解?

The problem is you are checking if the number is negative inside the for loop.问题是您正在检查 for 循环内的数字是否为负。 For instance if x=-3, then you are trying to run a for loop in range(2,-1) which is None.例如,如果 x=-3,那么您正在尝试在范围 (2,-1) 中运行一个 for 循环,该循环为 None。 So the for loop never runs and hence returns True.所以 for 循环永远不会运行,因此返回 True。

def isprime(x):
 if x<=0:
   return(False)
 for a in range(2,(x//2)+1):
   if(x%a==0):
     return(False)
 return(True)

By it's elementary school definition, prime numbers are defined for positive numbers only, thus your function should return False for every negative number, for example:根据小学定义,数仅针对正数定义,因此您的函数应该为每个负数返回False ,例如:

def isprime(x):
    if x <= 0:
        return False
    for a in range(2, (x//2)+1):
        if x % a == 0:
            return False
    return True

That being said, it is possible to extend the definition (as done in some fields in math), to include negative numbers as well (for further discussion see here and here ).话虽如此,可以扩展定义(如在数学中的某些领域所做的那样),也可以包括负数(有关进一步讨论,请参见此处此处)。 In this case, for every negative number -n , -n is prime iff n is prime.在这种情况下,对于每个负数-n-n是素数且仅当n是素数。 Therefore your code could be something like:因此,您的代码可能类似于:

def isprime(x):
    if x <= 0:   # or use any |abs| method you'd like, like numpy's
        x = -x
    for a in range(2, (x//2)+1):
        if x % a == 0:
            return False
    return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM