Simple Prime Number Generator in Python with Improved Logic
The given code aims to generate prime numbers but encounters issues. Here's an elaboration of the issues and a revised code with enhancements:
Problems and Solutions:
Here's the revised Python script:
import math def main(): count = 3 while True: isprime = True for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0: isprime = False break if isprime: print(count) count += 1
Optimized Sieve of Eratosthenes:
def gen_primes(): D = {} q = 2 while True: if q not in D: yield q D[q * q] = [q] else: for p in D[q]: D.setdefault(p + q, []).append(p) del D[q] q += 1
The above is the detailed content of How can I generate prime numbers in Python efficiently?. For more information, please follow other related articles on the PHP Chinese website!