Python Eratosthenes Sieve Algorithm Optimization

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

    I followed this link: Sieve of Eratosthenes - Finding Primes Python as suggested by @MAK and I've found that the accepted answer could be improved with an idea I've found in your code:

    def primes_sieve2(limit):
        a = [True] * limit               # Initialize the primality list
        a[0] = a[1] = False
        sqrt = int(math.sqrt(limit))+1
        for i in xrange(sqrt):
            isprime = a[i]
            if isprime:
                yield i
                for n in xrange(i*i, limit, i):     # Mark factors non-prime
                    a[n] = False
        for (i, isprime) in enumerate(a[sqrt:]):
            if isprime:
                yield i+sqrt
    

提交回复
热议问题