gpt4 book ai didi

python - 我的 is_prime 函数在 9 上失败了,我不知道为什么?

转载 作者:行者123 更新时间:2023-11-28 21:14:58 26 4
gpt4 key购买 nike

我有点问题。我正在编写一个 is_prime 函数,但每当我运行它时,它都会在 is_prime(9) 上失败,我不明白为什么:

def is_prime(x):
if x < 2: ##because negative numbers, 0 and 1 are not prime##
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
else:
return True

它在 is_prime(9) 上出于某种原因返回 True

最佳答案

这是因为该函数在返回之前不会检查所有 符合条件的除数。

相反,它提前退出 True如果x不能被 2 整除,这不是您想要的奇数(例如 9 不能被 2 整除,但它不是质数)。

相反,您想从 2 中尝试所有 可能的除数至 x-1 ,然后如果 x 则返回不能被它们整除。

为此,重写为:

def is_prime(x):
if x < 2: ##because negative numbers, 0 and 1 are not prime##
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
return True

关于python - 我的 is_prime 函数在 9 上失败了,我不知道为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30873392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com