Home >Backend Development >Python Tutorial >How can I generate prime numbers in Python efficiently?

How can I generate prime numbers in Python efficiently?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 04:07:49628browse

How can I generate prime numbers in Python efficiently?

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:

  • incorrect condition for printing primes: Replacing if count % x != 0 with if isprime, we print the prime numbers only.
  • incorrect loop handling: Using break instead of continue allows us to terminate the loop when a non-prime factor is encountered.
  • test range: Extending the range to int(math.sqrt(count) 1) ensures thorough testing.
  • optimized Sieve of Eratosthenes: For more efficient generation, the code incorporates the Sieve of Eratosthenes algorithm (separate code snippet provided for reference).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn