Home > Java > javaTutorial > How Can We Efficiently Generate Prime Numbers?

How Can We Efficiently Generate Prime Numbers?

Patricia Arquette
Release: 2024-11-03 20:43:02
Original
199 people have browsed it

How Can We Efficiently Generate Prime Numbers?

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

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!

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