python - 打印下一个 N 个质数

标签 python arrays primes

这个问题是一个 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/

相关文章:

python - pyodbc 删除 unicode 字符串

php - 如何从 MySQL 中检索 1 个随机行

c++ - 使用 vector 用 C++ 求解埃拉托色尼筛法并收到异常错误消息

java - 从数组中分离质数

Python SSL 导入错误

python - powershell tts 命令旁白使用 python 更改

c - 使用函数 findMax(int **a,int m, int n) 在矩阵中查找最大元素

c++ - 结构数组,其中包含数组。不会编译

python - 计算千次素数

python pandas groupby/应用 : what exactly is passed to the apply function?