Home > Web Front-end > JS Tutorial > How Can I Find Prime Numbers Between 0 and 100 in JavaScript?

How Can I Find Prime Numbers Between 0 and 100 in JavaScript?

Mary-Kate Olsen
Release: 2024-11-01 16:37:02
Original
935 people have browsed it

How Can I Find Prime Numbers Between 0 and 100 in JavaScript?

Finding Prime Numbers Between 0 and 100 in JavaScript

Identifying prime numbers within a given range can be a challenging task. While it may seem intuitive to check each number individually by using the modulus operator, this approach becomes inefficient, especially for larger ranges.

An Alternative Approach: Sieve of Eratosthenes

A more efficient algorithm for this problem is the Sieve of Eratosthenes. This method operates by iteratively eliminating non-prime numbers from a list of possible primes.

Implementation in JavaScript

<code class="javascript">function getPrimes(max) {
    var sieve = [], i, j, primes = [];
    for (i = 2; i <= max; ++i) {
        if (!sieve[i]) {
            // i has not been marked -- it is prime
            primes.push(i);
            for (j = i << 1; j <= max; j += i) {
                sieve[j] = true;
            }
        }
    }
    return primes;
}</code>
Copy after login

Usage

To find all prime numbers between 2 and 100:

<code class="javascript">var primes = getPrimes(100);
console.log(primes);</code>
Copy after login

Output:

[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ]
Copy after login

Conclusion

Using the Sieve of Eratosthenes provides a highly efficient and reliable method for finding prime numbers within a specified range. This approach dramatically improves performance compared to trial division and enables the identification of primes for even larger ranges.

The above is the detailed content of How Can I Find Prime Numbers Between 0 and 100 in JavaScript?. 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