I'm wanting to remove the non-prime numbers from an Array, the following is only removing the even numbers instead of the prime numbers.
function sumPrimes(num) {
//Produce an array containing all number of to and including num
let numArray = [];
for (let i = 1; i <= num; i++) {
numArray.push(i);
}
//Remove non-prime numbers from the array
numArray.map((number) => {
for (let i = 2; i < number; i++) {
if(number % i === 0) {
let index = numArray.indexOf(number);
return numArray.splice(index, 1);
}
}
});
return numArray;
}
sumPrimes(10);
This is currently returning:
[1, 2, 3, 5, 7, 9]
However, prime numbers are 1, 2, 3, 5, 7 (not include 9);
Use filter()
instead:
var numArray = [2, 3, 4, 5, 6, 7, 8, 9, 10] numArray = numArray.filter((number) => { for (var i = 2; i <= Math.sqrt(number); i++) { if (number % i === 0) return false; } return true; }); console.log(numArray);
The previous answer doesn't work correctly for negative numbers.
As you can see here , the simplest way to find prime numbers is:
const array = [-5, -3, -2, -1, ...Array(20).keys()]; // Array(20).keys() generates numbers from 0 to 19. function isPrime(num) { for (let start = 2; num > start; start++) { if (num % start == 0) { return false; } } return num > 1; } console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13, 17, 19]
The answer by Farnaz Kakhsaz works great, but it is slow. You only need to check until the root of 'num'. Thanks!
const array = [-5, -3, -2, -1, ...Array(20000).keys()];
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
console.log(array.filter(isPrime));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.