gpt4 book ai didi

javascript - 试图在数组中找到素数

转载 作者:行者123 更新时间:2023-11-30 11:35:40 26 4
gpt4 key购买 nike

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

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

最佳答案

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

关于javascript - 试图在数组中找到素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44533625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com