Why is my implementation of Sita Atkin with numbers close to the specified limit?

My implementation of Sito Atkin either skips primes near the limit or composites near the limit. while some restrictions work, while others do not. I am completely confused as to what is wrong.

def AtkinSieve (limit):
results = [2,3,5]
sieve = [False]*limit
factor = int(math.sqrt(lim))
for i in range(1,factor):
    for j in range(1, factor):
        n = 4*i**2+j**2
        if (n <= lim) and (n % 12 == 1 or n % 12 == 5):
            sieve[n] = not sieve[n]
        n = 3*i**2+j**2
        if (n <= lim) and (n % 12 == 7):
            sieve[n] = not sieve[n]
        if i>j:
            n = 3*i**2-j**2
            if (n <= lim) and (n % 12 == 11):
                sieve[n] = not sieve[n]
for index in range(5,factor):
    if sieve[index]:
        for jndex in range(index**2, limit, index**2):
            sieve[jndex] = False
for index in range(7,limit):
    if sieve[index]:
        results.append(index)
return results

For example, when I generate primes up to the limit of 1000, the Atkin sieve skips the prime 997 but includes the composite 965. But if I create the limit of 5000, the list it returns is completely correct.

+3
source share
1 answer

  • Change limto limit. Of course, you must have known this.
  • sieve = [False]*limit, - limit-1.

    if (n <= limit) and (n % 12 == 1 or n % 12 == 5):
    

    , n<=limit. n==limit, sieve[n] IndexError. limit (, n = 50). .

    sieve = [False]*(limit+1)
    

    , [0] . , , , sieve = [False]*limit, , sieve . (, sieve[n] sieve[n-1] ..). , . , / , , .

  • http://en.wikipedia.org/wiki/Sieve_of_Atkin, x [1, sqrt (limit)], .

    factor = int(math.sqrt(limit))
    

    int math.sqrt(limit). ,

    range(1,factor) 1 -1. , 1.

    ,

    factor = int(math.sqrt(limit))+1
    

  • N ( ) , .
def AtkinSieve (limit):
    results = [2,3,5]
    sieve = [False]*(limit+1)
    factor = int(math.sqrt(limit))+1
    for i in range(1,factor):
        for j in range(1, factor):
            n = 4*i**2+j**2
            if (n <= limit) and (n % 12 == 1 or n % 12 == 5):
                sieve[n] = not sieve[n]
            n = 3*i**2+j**2
            if (n <= limit) and (n % 12 == 7):
                sieve[n] = not sieve[n]
            if i>j:
                n = 3*i**2-j**2
                if (n <= limit) and (n % 12 == 11):
                    sieve[n] = not sieve[n]
    for index in range(5,factor):
        if sieve[index]:
            for jndex in range(index**2, limit, index**2):
                sieve[jndex] = False
    for index in range(7,limit):
        if sieve[index]:
            results.append(index)
    return results
+6

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


All Articles