Python Eratosthenes Sieve Algorithm Optimization

后端 未结 6 719
再見小時候
再見小時候 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条回答
  •  萌比男神i
    2020-12-21 14:05

    This code takes 2 seconds to generate primes less than 10M (it is not mine, i found it somewer on google)

    def erat_sieve(bound):
        if bound < 2:
            return []
        max_ndx = (bound - 1) // 2
        sieve = [True] * (max_ndx + 1)
        #loop up to square root
        for ndx in range(int(bound ** 0.5) // 2):
            # check for prime
            if sieve[ndx]:
                # unmark all odd multiples of the prime
                num = ndx * 2 + 3
                sieve[ndx+num:max_ndx:num] = [False] * ((max_ndx-ndx-num-1)//num + 1)
        # translate into numbers
        return [2] + [ndx * 2 + 3 for ndx in range(max_ndx) if sieve[ndx]]
    

提交回复
热议问题