Home > Article > Web Front-end > 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>
Usage
To find all prime numbers between 2 and 100:
<code class="javascript">var primes = getPrimes(100); console.log(primes);</code>
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 ]
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!