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

标签 javascript arrays

我正在做一个练习,对从 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/

相关文章:

javascript - Ajax 简单调用不起作用

javascript - 提交后如何获得 React Native TextInput 以保持焦点?

javascript - 浏览器与AJAX功能的兼容性

php - 基于 CSS 类动态填充 Javascript 数组?

javascript - 如何在 Angular.js 中的 JSON 对象中返回和排列

javascript - 无法在javascript中实现打印预览?

c - 为什么这个二维指针表示法有效而另一个无效

Javascript for 循环填充对象

c - 在C中对字符串数组进行排序

javascript - Protractor 变量重用效率