为什么我的Eratosthenes筛子不起作用? Python 3

Why is my Sieve of Erasthotenes not working? Python 3

这是我的代码。 我正在尝试制作一个有效但简单的Erasthotenes筛,但是当我运行该程序时,它只会不断返回整数,无论我放置了多大的范围。 这是在python 3。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
lyst = []
for i in range(2, 100):
    print(i)
    lyst.append(i)
count = 2
index = 1
for x in lyst:
    print(str(index) +" :" + str(count))
    if x%count == 0 and x != count:
        lyst.remove(x) #removing all multiples of count
    if max(lyst) == count: #breaks loop if count is the largest prime
        break
    else:
        count = lyst[lyst.index(count)+1] #turns count into next prime
    index += 1 #this is just for me to track how many primes i've found


x和count的值将始终具有相同的值:

  • 他们从价值2开始
  • 因此,remove将不会执行
  • 迭代结束时,计数将是列表中的下一个值,正好是下一次迭代开始时x的值

结论:它们在每次迭代开始时具有相同的值,因此永远不会满足if条件。

其次,Erasthotenes的筛子不应从筛子中除去元素,而应将某些值标记为非质数。它的作用是将值保持在其原始索引,因此.remove()并不是真正应该在普通筛算法中出现的。

为了找到正确的实现方式,您可以查看以下几个答案:

  • Eratosthenes筛-寻找Prime Python
  • Python中的快速素数筛
  • Python- Eratosthenes筛网-Compact Python
  • ... 还有更多。

这是您的代码和Wikipedia描述的混合:

1
2
3
4
5
6
7
8
9
n = 100
lyst = range(2, n)
for p in lyst:
    if not p:
        continue
    for i in range(2*p,n,p):
      lyst[i-2] = None
print [p for p in lyst if p]
#=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]


这应该做得到...看一下去除倍数的内循环:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
lyst = []
max = 100 # because ... you know, variables. ...
for i in range(2, max):
    lyst.append(i)
count = 2
index = 1
for x in lyst:
    print(str(index) +" :" + str(x)) # x is a prime number, so print it
    for y in lyst:
        if y>x and y%x == 0:
            lyst.remove(y)

    index += 1 #this is just for me to track how many primes i've found
print(index) # how many did we find