python prime numbers Sieve of Eratosthenes

前端 未结 6 982
旧时难觅i
旧时难觅i 2020-12-28 11:15

Hi can anyone tell me how to implement Sieve of Eratosthenes within this code to make it fast? Help will be really appreciated if you can complete it with sieve. I am really

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 12:03

    Fastest implementation I could think of

    def sieve(maxNum):
        yield 2
        D, q = {}, 3
        while q <= maxNum:
            p = D.pop(q, 0)
            if p:
                x = q + p
                while x in D: x += p
                D[x] = p
            else:
                yield q
                D[q*q] = 2*q
            q += 2
        raise StopIteration
    

    Source: http://code.activestate.com/recipes/117119-sieve-of-eratosthenes/#c4

    Replace this part

    import math
    def is_prime(n):
        if n == 2:
            return True
        if n%2 == 0 or n <= 1:
            return False
        sqr = int(math.sqrt(n)) + 1
        for divisor in range(3, sqr, 2):
            if n%divisor == 0:
                return False
        return True
    

    with

    primes = [prime for prime in sieve(10000000)]
    def is_prime(n):
        return n in primes
    

    Instead of 10000000 you can put whatever the maximum number till which you need prime numbers.

提交回复
热议问题