[英]Why is my prime number function not working?
I am new to programming and I face an issue while trying to write a program in finding out prime number. 我是编程新手,在尝试编写查找素数的程序时遇到问题。 Here is my code:
这是我的代码:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x-1):
if x % n == 0:
return False
else:
return True
I received an error stating "Your function fails on is_prime(3). It returns None when it should return True." 我收到一条错误消息,指出“您的函数在is_prime(3)上失败。在应返回True时返回None。”
Can someone please explain the flaw in this code? 有人可以解释一下此代码中的缺陷吗?
Thank you! 谢谢!
range()
has an exclusive upper bound , so it's trying to get the range between 2 and 2 (3 - 1), which is no elements. range()
有一个专有的上限 ,因此它试图获取2到2(3-1)之间的范围,该范围没有任何元素。 Since you can't iterate over nothing, the for loop never runs, so None
is returned (this is the default return type of a function if none is specified). 由于您无法遍历任何内容,因此for循环永远不会运行,因此将返回
None
(如果未指定,则为函数的默认返回类型)。
The solution to your immediate problem would be to use range(2, x)
rather than range(2, x - 1)
. 解决您当前问题的方法是使用
range(2, x)
而不是range(2, x - 1)
。 You'll find that you'll have problems at x > 3 though because as @khelwood said, you're returning True
or False
immediately after checking the first value. 您会发现在x> 3时会遇到问题,因为正如@khelwood所说,您在检查第一个值后立即返回
True
或False
。 Instead, only return True
after checking all values in the range. 相反,仅在检查范围内的所有值后才返回
True
。
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x): # range function will iterate till x-1
if x % n == 0:
return False
# return true only at the end after making sure it is not divisible by any number in the middle
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.