python prime numbers Sieve of Eratosthenes

前端 未结 6 980
旧时难觅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 11:52

    Here is a very fast generator with reduced memory usage.

    def pgen(maxnum): # Sieve of Eratosthenes generator
        yield 2
        np_f = {}
        for q in xrange(3, maxnum + 1, 2):
            f = np_f.pop(q, None)
            if f:
                while f != np_f.setdefault(q+f, f):
                    q += f
            else:
                yield q
                np = q*q
                if np < maxnum:  # does not add to dict beyond maxnum
                    np_f[np] = q+q
    
    def is_prime(n):
        return n in pgen(n)
    
    >>> is_prime(541)
    True
    >>> is_prime(539)
    False
    >>> 83 in pgen(100)
    True
    >>> list(pgen(100)) # List prime numbers less than or equal to 100
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
    89, 97]
    

提交回复
热议问题