这个问题是一个 friend 向我提出的。事情是这样的:- 给定两个整数 i 和 n,从 i 开始打印接下来的 n 个素数
注意:- 问题要求的是接下来的 n 个素数,并且没有指定范围,例如 i 到 n。
这是我想出来的,但不幸的是,它不起作用。你能帮忙吗?
def is_prime(Num):
prime = True
if Num > 1:
for i in range(2, Num):
if (Num % i) == 0:
prime = False
if prime:
return Num
if __name__ == "__main__":
startNum = int(input("Enter the first number: "))
primeNum = int(input("Enter the number of primes you want to print: "))
primeList = []
length = len(primeList)
while length <= primeNum:
x = is_prime(startNum)
primeList.append(x)
startNum = startNum + 1
length = length + 1
print(primeList)
print(x)
输出如下
Enter the first number: 3
Enter the number of primes you want to print: 5
[3, None, 5, None, 7, None]
None
最佳答案
关闭。您正在将 is_prime
的每个返回添加到列表中,无论它成功还是失败。将主循环替换为:
while len(primeList) <= primeNum:
if is_prime(startNum):
primeList.append(startNum)
startNum += 1
关于python - 打印下一个 N 个质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68749244/