Sieve of Eratosthenes - Finding Primes Python

前端 未结 17 2594
旧巷少年郎
旧巷少年郎 2020-11-22 04:40

Just to clarify, this is not a homework problem :)

I wanted to find primes for a math application I am building & came across Sieve of Eratosthenes approach.

17条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:06

    Removing from the beginning of an array (list) requires moving all of the items after it down. That means that removing every element from a list in this way starting from the front is an O(n^2) operation.

    You can do this much more efficiently with sets:

    def primes_sieve(limit):
        limitn = limit+1
        not_prime = set()
        primes = []
    
        for i in range(2, limitn):
            if i in not_prime:
                continue
    
            for f in range(i*2, limitn, i):
                not_prime.add(f)
    
            primes.append(i)
    
        return primes
    
    print primes_sieve(1000000)
    

    ... or alternatively, avoid having to rearrange the list:

    def primes_sieve(limit):
        limitn = limit+1
        not_prime = [False] * limitn
        primes = []
    
        for i in range(2, limitn):
            if not_prime[i]:
                continue
            for f in xrange(i*2, limitn, i):
                not_prime[f] = True
    
            primes.append(i)
    
        return primes
    

提交回复
热议问题