Quantcast
Viewing latest article 10
Browse Latest Browse All 28

Answer by storm125 for Sieve of Eratosthenes - Finding Primes Python

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 npdef 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 primesprint(len(primes(100_000_000)))

Viewing latest article 10
Browse Latest Browse All 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>