Home >Backend Development >Python Tutorial >How Can We Optimize the Sieve of Eratosthenes Algorithm in Python for Faster Prime Number Generation?
Sieve of Eratosthenes - Finding Primes in Python
Problem:
While attempting to implement the Sieve of Eratosthenes algorithm in Python, users often encounter slow execution times, particularly when searching for primes above 1 million.
Solution:
The given implementation presents several areas for improvement:
1. Unoptimized Algorithm:
2. List Manipulation Inefficiency:
Optimized Implementation:
To resolve these issues, consider the following optimized implementation:
def primes_sieve2(limit): a = [True] * limit a[0] = a[1] = False for (i, isprime) in enumerate(a): if isprime: yield i for n in range(i*i, limit, i): # Mark factors non-prime a[n] = False
Key Improvements:
The above is the detailed content of How Can We Optimize the Sieve of Eratosthenes Algorithm in Python for Faster Prime Number Generation?. For more information, please follow other related articles on the PHP Chinese website!