我正试图想出一种算法,可以找到从一个起始数到一个结束数的所有素数,而不需要从2开始,使用埃拉托什尼筛来计算到结束数的所有素数,并裁剪出我想要的区间.而不是粗暴地对待间隔中的每一个数字.

我修改了python中Eratosthenes筛的现有符号.到目前为止,我得到的是:

def m(n: int, l: list):
    for i, v in enumerate(l):
        if v % n == 0 and v != n and v != False:
            break
    for v in range(i, len(l), n):
        l[v] = False
    return l

该函数可以将数组l中数字n的所有公倍数设置为false,使用与标记非素数时的Eratosthenes筛相同的原理.

l = list(range(10, 20))
for i in range(2, 20):
    m(i, l)
print(l)

在此配置中,程序计算从10到(不包括)20的所有素数.

输出如下所示:

[False, 11, False, 13, False, False, False, 17, False, False]

但它应该是这样的:

[False, 11, False, 13, False, False, False, 17, False, 19]

似乎数组的最后一个素数被忽略了.当我试图从10计算到(排除)21时,它检测到19是素数.

我做错了什么?

推荐答案

对于您的特定用例,19被False覆盖.在第二个循环开始之前,我添加了一个小的回退/理智判断.你可以通过我的print个日志(log)看到发生了什么:

def m(n: int, l: list):
    # set i to its max value
    broke_out = False
    for i, v in enumerate(l):
        if v % n == 0 and v != n and v != False:
            print(f"breaking on index :{i}")
            broke_out = True
            break
    # SANITY CHECK: if we never broke out of the above loop and we're on the last index, we're done.
    if not broke_out and i == len(l)-1:
        return l
    # now use i as the starting point in this loop
    for x in range(i, len(l), n):
        # if not isinstance(x, int):
        print(f"about to overwrite l[x] which is: {l[x]} where x is: {x}")
        # if l[x] % n == 0:
        l[x] = False
    print(f"State of l before returning : {l}")
    return l

l = list(range(10, 20))

for i in range(2, 20):
    m(i, l)

print(l)

完整输出:

breaking on index :0
about to overwrite l[x] which is: 10 where x is: 0
about to overwrite l[x] which is: 12 where x is: 2
about to overwrite l[x] which is: 14 where x is: 4
about to overwrite l[x] which is: 16 where x is: 6
about to overwrite l[x] which is: 18 where x is: 8
State of l before returning : [False, 11, False, 13, False, 15, False, 17, False, 19]
breaking on index :5
about to overwrite l[x] which is: 15 where x is: 5
about to overwrite l[x] which is: False where x is: 8
State of l before returning : [False, 11, False, 13, False, False, False, 17, False, 19]
[False, 11, False, 13, False, False, False, 17, False, 19]
[Finished in 0.1s]

Python相关问答推荐

使用numpy提取数据块

将特定列信息移动到当前行下的新行

对于一个给定的数字,找出一个整数的最小和最大可能的和

使用groupby Pandas的一些操作

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

如何在WSL2中更新Python到最新版本(3.12.2)?

计算每个IP的平均值

python中字符串的条件替换

从源代码显示不同的输出(机器学习)(Python)

为什么t sns.barplot图例不显示所有值?'

如何获得3D点的平移和旋转,给定的点已经旋转?

如何重新组织我的Pandas DataFrame,使列名成为列值?

在第一次调用时使用不同行为的re. sub的最佳方式

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

无法在盐流道中获得柱子

根据过滤后的牛郎星图表中的数据计算新系列

如何获取给定列中包含特定值的行号?

合并Pandas中的数据帧,但处理不存在的列

基于2级列表的Pandas 切片3级多索引

判断字典键、值对是否满足用户定义的搜索条件