Python 我的素性测试忽略了一个条件。我做错了什么?
作为一个python新手爱好者,我觉得这很烦人:Python 我的素性测试忽略了一个条件。我做错了什么?,python,loops,Python,Loops,作为一个python新手爱好者,我觉得这很烦人: def isPrime(x): if x < 0: raise Exception("The number is negative.") if x == 0 or x == 1: return False if x == 2: return True else: if x % 2 == 0: return False for i in xrange (3, int(math.s
def isPrime(x):
if x < 0: raise Exception("The number is negative.")
if x == 0 or x == 1: return False
if x == 2: return True
else:
if x % 2 == 0: return False
for i in xrange (3, int(math.sqrt(x)), 2): #-------> This doesn't do anything.
if x % i == 0: return False # Even if I put 3 instead of i, it still prints numbers that are divisible by 3.
return True
for i in xrange (100):
if isPrime(i):
print i
def isPrime(x):
如果x<0:引发异常(“数字为负数”)
如果x==0或x==1:返回False
如果x==2:返回True
其他:
如果x%2==0:返回False
对于xrange中的i(3,int(math.sqrt(x)),2):#----->这没有任何作用。
如果x%i==0:返回False#即使我输入3而不是i,它仍然打印可被3整除的数字。
返回真值
对于X范围内的i(100):
如果是(i):
打印i
我得到像9,15,21这样的数字-可以被3整除,因此不是素数。我遗漏了什么?您想要xrange(3,int(math.sqrt(x))+1,2)
-请记住xrange
迭代所有值,从其起点(包含)到终点(独占)
更具体地说,当
x
为9时,就有了xrange(3,3,2)
,它不会迭代任何东西。捕捉得好!为了OP的利益,这被称为。这很常见,足以证明它自己的维基百科文章是正确的。