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

How to Find Prime Numbers Between 0 and 100 in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 20:00:03286browse

How to Find Prime Numbers Between 0 and 100 in JavaScript?

Finding Prime Numbers Between 0 and 100 in JavaScript

Identifying prime numbers within a specified range can be a challenging task, especially when using a modulus approach. To overcome this issue, consider employing a more efficient method known as the Sieve of Eratosthenes.

Sieve of Eratosthenes Implementation in JavaScript:

The following JavaScript implementation uses the Sieve of Eratosthenes algorithm to find prime numbers:

<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>

By calling getPrimes(100), you can retrieve an array containing all prime numbers between 2 and 100 (inclusive). This method provides a more efficient and scalable approach compared to the modulus approach mentioned in the original question.

Usage:

<code class="javascript">var primeNumbers = getPrimes(100);
console.log(primeNumbers); // prints [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]</code>

The above is the detailed content of How to Find Prime Numbers Between 0 and 100 in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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