Python Eratosthenes Sieve Algorithm Optimization

后端 未结 6 738
再見小時候
再見小時候 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:45

    if given unlimited memory and time, the following code will print all the prime numbers. and it'll do it without using trial division. it is based on the haskell code in the paper: The Genuine Sieve of Eratosthenes by Melissa E. O'Neill

    from heapq import heappush, heappop, heapreplace
    def sieve():
        w = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
        for p in [2,3,5,7]: print p
        n,o = 11,0
        t = []
        l = len(w)
        p = n
        heappush(t, (p*p, n,o,p))
        print p
        while True:
            n,o = n+w[o],(o+1)%l
            p = n
            if not t[0][0] <= p:
                heappush(t, (p*p, n,o,p))
                print p
                continue
            while t[0][0] <= p:
                _, b,c,d = t[0]
                b,c = b+w[c],(c+1)%l
                heapreplace(t, (b*d, b,c,d))
    sieve()
    

提交回复
热议问题