Home >Web Front-end >JS Tutorial >How to Efficiently Find Prime Numbers Within a Range in JavaScript?

How to Efficiently Find Prime Numbers Within a Range in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 22:49:30357browse

How to Efficiently Find Prime Numbers Within a Range in JavaScript?

Efficiently Find Prime Numbers within a Range

In JavaScript, identifying prime numbers between a specified range can be achieved through various methods. One commonly used approach is the Sieve of Eratosthenes algorithm. This technique marks multiples of primes as non-prime, allowing for the efficient identification of prime numbers.

The following is a JavaScript implementation of a modified Sieve of Eratosthenes algorithm to find prime numbers within the range of 0 to 100:

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

In this function, an array named 'sieve' is used to track numbers marked as non-prime. Iterating through numbers from 2 to the maximum specified, unmarked numbers are considered prime and added to the 'primes' array. Multiples of primes are subsequently marked as non-prime in the 'sieve' array.

By utilizing this function, you can efficiently retrieve all prime numbers within a specified range. For instance, getPrimes(100) will return an array of all primes between 2 and 100 (inclusive).

The above is the detailed content of How to Efficiently Find Prime Numbers Within a Range 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