gpt4 book ai didi

python - 求素数函数

转载 作者:行者123 更新时间:2023-11-28 22:03:49 25 4
gpt4 key购买 nike

我有一个函数:

def containsNoDivisor(n, ps):
'''n is an integer and ps is a list of integers. Returns True if
and only if there is no integer in ps that divides n. '''
for p in ps:
if n % p == 0:
return False
print True

然后我需要创建另一个函数,它根据上面的函数计算一个 < n 的素数列表。到目前为止,我有:

def findPrimes(n):
primes = [2]
for i in range(3,n):
if containsNoDivisor(i, primes):
primes.append(i)
return primes

但它返回的是 True 而不是质数?

最佳答案

看起来您正在打印 True 而不是在您的 containsNoDivisor 函数中返回它。它应该看起来像这样:

def containsNoDivisor(n, ps):
'''n is an integer and ps is a list of integers. Returns True if
and only if there is no integer in ps that divides n. '''
for p in ps:
if n % p == 0:
return False
return True

print 语句只是将值输出到控制台 - 如果您在交互式 shell 中尝试每个函数,这是一个很容易犯的错误。 return 将实际获取值并将其传递回调用它的任何对象,从而允许在创建或处理它的函数之外使用数据。

关于python - 求素数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8342657/

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