Home > Article > Web Front-end > How to Find All Prime Numbers Between 0 and 100 Using the Sieve of Eratosthenes in JavaScript?
In the realm of JavaScript, identifying prime numbers within a given range is a computational challenge. For those unfamiliar with prime numbers, they are positive integers divisible only by 1 and themselves.
One approach to finding primes is to use the Sieve of Eratosthenes algorithm. This method commences with creating an array of integers from 0 to the desired upper bound, in this case 100. Subsequently, the array elements corresponding to non-prime numbers are marked as composite.
The algorithm commences by setting the element at index 1 to 0, indicating that 1 is not prime. It then proceeds to iterate through the array, marking all multiples of each prime number as non-prime. For instance, if the current prime is 2, all multiples of 2 (except 2 itself) are marked as composite. This process continues until all primes up to the square root of the upper bound have been processed.
Here's a JavaScript implementation of the Sieve of Eratosthenes algorithm:
<code class="js">function getPrimes(max) { var sieve = [], i, j, primes = []; for (i = 2; i <= max; ++i) { if (!sieve[i]) { primes.push(i); for (j = i << 1; j <= max; j += i) { sieve[j] = true; } } } return primes; } console.log(getPrimes(100));</code>
Running this function will generate an array containing all prime numbers between 2 and 100 (inclusive). This method efficiently determines prime numbers within a specified range using a comprehensive approach.
The above is the detailed content of How to Find All Prime Numbers Between 0 and 100 Using the Sieve of Eratosthenes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!