[英]Prime number checking function not working on a test case
I'm fairly new to coding but I'm having an issue with my code.我对编码很陌生,但我的代码有问题。 The code seems to work with every test number and I can tell why.
该代码似乎适用于每个测试编号,我可以说出原因。
num1 = int(input('Please enter a positive integer: '))
def is_prime(x):
if x <= 1 :
return False
elif x == 2:
return True
for n in range(3,x-1,2):
if x % n == 0:
return False
return True
print(is_prime(num1))
4
is returning a True
value when it should be False
. 4
在应该为False
时返回True
值。
This is your culprit:这是你的罪魁祸首:
for n in range(3,x-1,2):
if x % n == 0:
return False
return True
Your step term in range
is 2 starting at 3, so 4 doesn't get tested.您的
range
的步长项是从 3 开始的 2,因此未测试 4。 Because it isn't tested, your function just returns True
.因为它没有经过测试,所以您的 function 只会返回
True
。
You can fix this naively by adding another elif
checking input mod 2 before your range.您可以通过在您的范围之前添加另一个
elif
检查输入 mod 2 来天真地解决此问题。
def is_prime(x):
if x <= 1 :
return False
elif x == 2:
return True
elif x % 2 == 0:
return False
for n in range(3,x-1,2):
if x % n == 0:
return False
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.