How can I generate prime numbers in Python efficiently?

Susan Sarandon
Release: 2024-11-13 04:07:49
Original
572 people have browsed it

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template