问题
I have a simple problem: take a number and determine if it is prime. I cannot figure out why on earth the following does not work.
def prime(x):
for i in range (2, x):
if x % i == 0:
return False
return True
prime(21)
This returns true! I have no idea why.
回答1:
In your code you have put return True
inside the for loop, so it only checks whether the number is divisible by two and if not, it returns true.
Rather use this
def prime(x):
for i in range (2, x):
if x % i == 0:
return False
return True
Also to improve efficiency a bit use
for i in range (2, int(x/2)+1)
since once you have reached x/2 no number after that can divide it anyhow.
In future try debugging your code by printing values of loop indexes where it defaults or using a debugger, it is real helpful and helps you improve as a programmer.
来源:https://stackoverflow.com/questions/54473512/determining-if-a-number-is-prime-in-the-above-code