gpt4 book ai didi

javascript - 我如何求和所有素数?

转载 作者:行者123 更新时间:2023-11-29 21:46:27 25 4
gpt4 key购买 nike

我正在做一个练习,对从 2 到参数的所有质数求和。我已经在代码中工作了这么远,但被卡住了。我相信通过使用 splice 函数,我实际上是在跳过一个元素,因为索引发生了变化。

function sumPrimes(num) {
var primearray = [];
var sum = 0;
for(var i =2; i <= num; i++){
primearray.push(i);
}

for(var j = 0; j < primearray.length; j++) {
console.log(primearray[j]);
if ((primearray[j]%2===0) && (primearray[j] >2)) {
primearray.splice(j,1);
} else if ((primearray[j]%3===0) && (primearray[j] > 3)) {
primearray.splice(j,1);
console.log(primearray);
} else if ((primearray[j]%5===0) && (primearray[j] > 5)) {
primearray.splice(j,1);
} else if ((primearray[j]%7===0) && (primearray[j] > 7)) {
primearray.splice(j,1);
}
}
sum = primearray.reduce();
return sum;
}

sumPrimes(30);

我还没有使用 reduce 函数,因为我还在处理 if else 语句。

最佳答案

对于同样的问题,我找到了一个很好的解决方案。 afmeva 就在现场。这就是它的工作原理。

function isPrime(val){

//test if number is prime
for(var i=2; i < val; i++){
if(val % i === 0){
return false;
}
}
return true;
}

In the above code we accept a number to determine whether or not it is prime. We then loop from two all the way up until our number minus one because we know that our number will be divisible by itself and one. If the remainder of our value with the current loop value is zero then we know it is not prime so break out and say so.

This article explains very well

function sumPrimes(num) {
var answer = 0;

//loop through all numbers from 2 to input value

for(var i=2; i <= num; i++){

//sum only prime numbers, skip all others
if(isPrime(i)){
answer += i;
}
}
return answer;
}

sumPrimes(977); // 73156

Here's another good resource

关于javascript - 我如何求和所有素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31032165/

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