Sieve of Eratosthenes - Finding Primes Python

前端 未结 17 2303
旧巷少年郎
旧巷少年郎 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条回答
  •  长情又很酷
    2020-11-22 05:11

    Using a bit of numpy, I could find all primes below 100 million in a little over 2 seconds.

    There are two key features one should note

    • Cut out multiples of i only for i up to root of n
    • Setting multiples of i to False using x[2*i::i] = False is much faster than an explicit python for loop.

    These two significantly speed up your code. For limits below one million, there is no perceptible running time.

    import numpy as np
    
    def primes(n):
        x = np.ones((n+1,), dtype=np.bool)
        x[0] = False
        x[1] = False
        for i in range(2, int(n**0.5)+1):
            if x[i]:
                x[2*i::i] = False
    
        primes = np.where(x == True)[0]
        return primes
    
    print(len(primes(100_000_000)))
    

提交回复
热议问题