Python Eratosthenes Sieve Algorithm Optimization

后端 未结 6 631
再見小時候
再見小時候 2020-12-21 13:09

I\'m attempting to implement the Sieve of Eratosthenes. The output seems to be correct (minus \"2\" that needs to be added) but if the input to the function is larger than 1

6条回答
  •  生来不讨喜
    2020-12-21 13:57

    Your algorithm is not the Sieve of Eratosthenes. You perform trial division (the modulus operator) instead of crossing-off multiples, as Eratosthenes did over two thousand years ago. Here is an explanation of the true sieving algorithm, and shown below is my simple, straight forward implementation, which returns a list of primes not exceeding n:

    def sieve(n):
        m = (n-1) // 2
        b = [True]*m
        i,p,ps = 0,3,[2]
        while p*p < n:
            if b[i]:
                ps.append(p)
                j = 2*i*i + 6*i + 3
                while j < m:
                    b[j] = False
                    j = j + 2*i + 3
            i+=1; p+=2
        while i < m:
            if b[i]:
                ps.append(p)
            i+=1; p+=2
        return ps
    

    We sieve only on the odd numbers, stopping at the square root of n. The odd-looking calculations on j map between the integers being sieved 3, 5, 7, 9, ... and indexes 0, 1, 2, 3, ... in the b array of bits.

    You can see this function in action at http://ideone.com/YTaMB, where it computes the primes to a million in less than a second.

提交回复
热议问题