试图在数组中找到Prime数字

时间:2017-06-14 00:40:31

标签: javascript

我想要从数组中删除非素数,以下只删除偶数而不是素数。

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);

目前正在返回:

[1, 2, 3, 5, 7, 9]

然而,素数是1,2,3,5,7(不包括9);

3 个答案:

答案 0 :(得分:2)

改为使用filter()

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);

答案 1 :(得分:1)

Farnaz Kakhsaz的回答很好,但很慢。您只需要检查直到'num'的根即可。谢谢!

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));

答案 2 :(得分:0)

previous answer对于负数不能正常工作。

您会看到here,查找质数的最简单方法是:

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]