gpt4 book ai didi

python - 检查数字在 python 中是质数,为什么要检查 int(sqrt(n)-1)) 而不是 int(sqrt(n))

转载 作者:行者123 更新时间:2023-11-28 21:50:09 29 4
gpt4 key购买 nike

这里是 Python 的新手。我试图了解此函数如何检查素数:

from itertools import count, islice
from math import sqrt
def is_prime(n):
if n < 2: return False
return all(n%i for i in islice(count(2), int(sqrt(n)-1)))

据我了解,您可以检查小于等于并包括 n 的平方根的因子,那么为什么这只测试小于等于 sqrt(n)-1 的因素?我也不清楚函数的 return all 部分。 n%i 返回一个 int,余数。那么为什么这个表达式的计算结果是 bool 值呢?对此的任何指示都会很棒。谢谢!

最佳答案

因为 islice 的第二个参数是一个计数,而不是停止的值。

xrange(2, int(sqrt(n))+1) 会好得多

这里的加一是使范围包含两端,而 xrange 通常不是。

关于python - 检查数字在 python 中是质数,为什么要检查 int(sqrt(n)-1)) 而不是 int(sqrt(n)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284130/

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