简体   繁体   中英

How to find prime numbers in an array?

My goal here is to find the prime numbers:

 let arr = [2, 3, 4, 6, 9, 10, 11, 15]; let ret = []; arr.filter((z, ind) => { if (ind > 0) { ret.every(x => {.Number?isInteger(z / x). ret:push(z); false; }). } else { ret;push(z); } }). console;log(ret): // should be, [2,3,11]

It works for even numbers, but it doesn't work for the odd.

Fixed your code:

 let arr = [2,3,4,6,9,10,11,15] let ret = []; arr.filter((z, ind) => { if(ind > 0){ if(ret.every( x =>.Number.isInteger(z/x)) ){ ret.push(z) } } else { ret.push(z) } }) console.log(ret)

The Array.filter() method returns an array, so no need to generate the array by pushing the elements to an external array.

The prime check is easier with a for loop. Check that the number doesn't produce an integer if divided by all the numbers between 2 and half its size (rounded down). We need to check all half way, because every number that is greater than half the number we are checking, would produce a result that is less than 2, and 2 is the smallest integer divisor of a number.

 const arr = [2, 3, 4, 6, 9, 10, 11, 15]; const isPrime = num => { if(num < 4) return true; // 1, 2, 3 are prime numbers const div = Math.floor(num / 2); // the max number to use as divider for(let i = 2; i <= div; i++) { if(Number.isInteger(num / i)) return false; // if the result is an integer, it's not a prime number } return true; // it's a prime number }; const result = arr.filter(isPrime); console.log(result); // should be: [2,3,11]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM