作为一个新手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
Run Code Online (Sandbox Code Playgroud)
我得到像9,15,21这样的数字 - 可被3整除,因此不是素数.我错过了什么?
Saj*_*ngh 11
你想要xrange (3, int(math.sqrt(x)) + 1, 2)- 记住,xrange遍历所有值,从它的起点(包括它)到它的停止点,独占.
更具体地说,当它x是9时,你xrange (3, 3, 2)没有迭代任何东西.