Generate Prime Numbers with Elegance and Efficiency
In the realm of programming, finding an elegant and efficient way to generate prime numbers is a classic challenge. Let's explore an approach that strikes a balance between conciseness and performance.
Consider using the prime number theorem, which estimates the number of primes less than or equal to n as pi(n) ≈ n / log(n). This estimate provides an upper bound on the size of a sieve that can be used to identify the primes.
The sieve method, also known as the Sieve of Eratosthenes, iterates through a range of numbers and eliminates all non-primes by marking them as composite. For this task, we can utilize a BitSet to represent the set of primes, with each bit corresponding to a number in the range.
Below is a Java implementation of this elegant and efficient prime number generation method:
<code class="java">public static BitSet computePrimes(int limit) { BitSet primes = new BitSet(); primes.set(0, false); primes.set(1, false); primes.set(2, limit, true); for (int i = 0; i * i < limit; i++) { if (primes.get(i)) { for (int j = i * i; j < limit; j += i) { primes.clear(j); } } } return primes; }</code>
This method efficiently generates the first million primes in approximately a second on a typical laptop. Its combination of precision and speed makes it a valuable tool for generating prime numbers in various computing scenarios.
The above is the detailed content of How Can We Efficiently Generate Prime Numbers?. For more information, please follow other related articles on the PHP Chinese website!