查找素数的 Python 程序 (3.5)

标签 python python-3.x

我正在编写一个查找素数的程序。要求用户提供一个大于 2 (n) 的数字,然后程序会生成一个从 2 开始到用户数字 (n) 结束的列表。在我的程序中,我应该将一个名为 current 的变量设置为 2,然后循环遍历列表,查找 current 的倍数并将其删除。在循环结束时,我将 1 添加到 current 中,程序再次循环执行与之前相同的操作。每次都会打印该列表。我的程序工作正常(我正在使用数字 10 作为 n 进行测试),当它到达末尾时,即使它应该被删除,仍然留下 10 。请帮忙。

这是我的代码:

while True:
    global n
    n = int ( input ( "Please enter a number larger than 2. " ) )
    if n > 2:
        break
    else:
        print ( "Your number is not larger than 2." )
        continue

current = 2
myList = list ( range ( 2, n + 1 ) )
while current < n:
    if current == []:
        break
    for i in reversed ( range ( len( myList )-1 ) ):
        if myList[i] % current == 0 and myList[i] != current and ( myList[i] / current ).is_integer(): myList.pop(i)
        print ( myList )
    current = current + 1

最佳答案

对于反向的 i ( range ( len( myList )-1 ) ): 应该是 对于反向的 i ( range ( len( myList ) ) ):

默认情况下范围不包括最后一个数字:range(5) 给出 0,1,2,3,4

要使其在发生更改时仅输出一行:

if myList[i] % current == 0 and myList[i] != current and ( myList[i] / current ).is_integer():
    myList.pop(i)
    print ( myList )

如果您在 if 语句中进行打印,那么只有当它发生更改时才会显示新列表。

关于查找素数的 Python 程序 (3.5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920561/

相关文章:

python - 如何在 Pandas 的开头和结尾添加零值?

python-3.x - 如何在不编码的情况下将字符串转换为字节

python-3.x - 在一个解释器中获取 TypeError(元组分配),而不是另一个

python-3.x - 轴对齐边界框Skimage

python - 在 "with"上下文中同时打开两个文件

python - Tornado 的 ORM

python - numpy 中的内置函数将 Integer 解释为索引 = 整数值集的 numpy 数组

python - 如何使用 virtualenv 为 Python 3.7 创建虚拟环境,而无需在我的计算机(Ubuntu 16.04.6 LTS x64)上安装 Python 3.7?

python - 如何使用 get_object_or_404 和 order_by ('?' ) 来获取随机图像

Python 电话号码正则表达式