作为一名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.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我得到像9,15,21这样的数字-可以被3整除,因此不是素数。我遗漏了什么?
发布于 2013-07-02 08:07:03
你想要xrange (3, int(math.sqrt(x)) + 1, 2) --记住,xrange会遍历所有的值,从它的起始点(包含)到它的终止点(不包含)。
更具体地说,当x为9时,您有xrange (3, 3, 2),它不会迭代任何内容。
https://stackoverflow.com/questions/17415495
复制相似问题