Home > Backend Development > Python Tutorial > What's the Fastest Algorithm to Generate All Prime Numbers Below a Given Integer N?

What's the Fastest Algorithm to Generate All Prime Numbers Below a Given Integer N?

DDD
Release: 2024-12-18 02:35:10
Original
619 people have browsed it

What's the Fastest Algorithm to Generate All Prime Numbers Below a Given Integer N?

Fastest Way to List All Primes Below N: An Exploration

Problem:

Determine the fastest method to list all prime numbers less than a given integer N.

Question:

Can the given algorithm be optimized for faster execution?

Answer:

The provided algorithm can be significantly improved for speed. A comparison of various implementations reveals that rwh_primes1 with Psyco is the most efficient for generating primes less than 1,000,000.

Additional Findings:

  • Without Psyco, rwh_primes2 emerges as the fastest method.
  • Utilizing NumPy offers further performance enhancements, with primesfrom2to proving to be the fastest among all tested methods.

Implementation Details:

  • ambi_sieve_plain: A straightforward sieve-based approach.
  • rwh_primes, rwh_primes1, and rwh_primes2: Variations of Robert William Hanks' algorithms.
  • sieve_wheel_30: A specialized algorithm optimized for 30-based calculations.
  • sieveOfEratosthenes: The classic sieve method with bitset optimizations.
  • sieveOfAtkin: A modern sieve utilizing modulo arithmetic.
  • sundaram3: Sundaram's algorithm with optimizations for sets of smaller numbers.
  • ambi_sieve: A sieve-based approach with NumPy optimizations.
  • primesfrom3to and primesfrom2to: NumPy-based algorithms for efficiently generating primes.

Timings:

Method Time (ms) with Psyco Time (ms) without Psyco
rwh_primes1 43.0 93.7
sieveOfAtkin 46.4 314.0
rwh_primes 57.4 94.6
sieve_wheel_30 63.0 97.4
rwh_primes2 67.8 68.1
sieveOfEratosthenes 147.0 178.0
ambi_sieve_plain 152.0 286.0
sundaram3 194.0 416.0
primesfrom2to
Method Time (ms) with Psyco Time (ms) without Psyco
rwh_primes1 43.0 93.7
sieveOfAtkin 46.4 314.0
rwh_primes 57.4 94.6
sieve_wheel_30 63.0 97.4
rwh_primes2 67.8 68.1
sieveOfEratosthenes 147.0 178.0
ambi_sieve_plain 152.0 286.0
sundaram3 194.0 416.0
primesfrom2to 15.9 N/A
primesfrom3to 18.4 N/A
ambi_sieve 29.3 N/A
15.9
N/A
primesfrom3to 18.4 N/A
ambi_sieve 29.3 N/A

The above is the detailed content of What's the Fastest Algorithm to Generate All Prime Numbers Below a Given Integer N?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template