The Eratosthenes sieve returns a large composite number (which is a mistake)

I am implementing the Eratosthenes sieve in Python. It returns compound numbers at the end of the search range:

def primes_Ero(n=1000):
    primes = []
    a = [True]*(n+1)
    a[0] = a[1] = False
    for (i,isprime) in enumerate(a):
        if isprime:
            for n in range(i*i,n+1, i):          
                a[n] = False
            primes.append(i)
    return primes

When using large numbers n, I get combined numbers. I checked to see which numbers are compound (compared to brute force),

Given n, which numbers are composite:

n= 100; []
n= 500; [493, 497]
n= 1000; [961, 989]
n= 10000; [9701, 9727, 9797, 9853, 9869, 9917, 9943, 9953, 9983, 9991, 9997]

What am I doing wrong?

+4
source share
1 answer

The problem is this line:

 for n in range(i*i, n+1, i):

n ( = 1000), , for , n i < n < i + n. , for , .

n, . , , sieve_size, , .

, , , , , , . .

+4

Source: https://habr.com/ru/post/1670689/


All Articles