
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Using Sieve of Eratosthenes to find primes JavaScript
We are required to write a JavaScript function that takes in a number, say n.
The function should return an array of all the prime numbers between 1 and n.
Approach
The first step is to create an array as large as the given number, with all its values initialized as true. The array indexes will represent all the possible prime numbers, with all being true at the beginning.
Then, we create a for loop that iterates from 2 to the square root of the given number. By definition, products of any integer cannot be prime, while 0 and 1 are ignored because divisibility by them does not affect primality.
Lastly, we can simply filter out all the false values to arrive at all the prime numbers.
Example
const num = 100; const findPrimes = (num = 10) => { const numArr = new Array(num + 1); numArr.fill(true); numArr[0] = numArr[1] = false; for (let i = 2; i <= Math.sqrt(num); i++) { for (let j = 2; i * j <= num; j++){ numArr[i * j] = false; } } return numArr.reduce((acc, val, ind) => { if(val){ return acc.concat(ind); }else{ return acc; }; },[]); }; console.log(findPrimes(num));
Output
And the output in the console will be −
[ 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 ]
- Related Questions & Answers
- Sieve of Eratosthenes in java
- Python Program for Sieve of Eratosthenes
- Java Program to get prime numbers using the Sieve of Eratosthenes algorithm
- C++ Program to Implement Sieve of eratosthenes to Generate Prime Numbers Between Given Range
- Find the Number of Primes In A Subarray using C++
- Filtering out primes from an array - JavaScript
- Find the sum of all Truncatable primes below N in Python
- Bitwise Sieve in C++
- Representing number as the power and product of primes in JavaScript
- C++ Program to Generate Prime Numbers Between a Given Range Using the Sieve of Sundaram
- Count Primes in Python
- Prime Factorization using Sieve O(log n) for multiple queries in C++
- C++ Program to Implement Sieve of Atkin to Generate Prime Numbers Between Given Range
- Count number of primes in an array in C++
- Find number of spaces in a string using JavaScript
Advertisements