简体   繁体   English

我如何总结所有质数?

[英]How do I sum all prime numbers?

I am working on an excercise to sum all prime numbers from 2 to the parameter.我正在做一个练习来总结从 2 到参数的所有素数。 I have worked this far in the code, but am stuck.我已经在代码中工作了这么远,但被卡住了。 I believe by using the splice function, I am actually skipping an element because of a changed indices.我相信通过使用 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);

I haven't utilized the reduce function yet because I am still working on the if else statements.我还没有使用过 reduce 函数,因为我还在处理 if else 语句。

I found a pretty good solution to the same problem.对于同样的问题,我找到了一个很好的解决方案。 afmeva was spot on. afmeva 恰到好处。 This is how it works.这就是它的工作原理。

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.然后我们从 2 一直循环到我们的数字减 1,因为我们知道我们的数字可以被它自身和 1 整除。 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 这是另一个很好的资源

 function sumPrimes(num) { let arr = Array.from({length: num+1}, (v, k) => k).slice(2); let onlyPrimes = arr.filter( (n) => { let m = n-1; while (m > 1 && m >= Math.sqrt(n)) { if ((n % m) === 0) return false; m--; } return true; }); return onlyPrimes.reduce((a,b) => a+b); } sumPrimes(977);

I have seen lots of people putting all prime numbers into arrays and in order to check if a number is prime, they check from 2 to the number to see if there's a remainder.我见过很多人将所有素数放入数组中,为了检查一个数是否为素数,他们会检查从 2 到该数是否有余数。 You only need to check odd numbers, and only need to count to half the number because a number can't be divisible by any number greater than it has.你只需要检查奇数,只需要数到它的一半,因为一个数字不能被任何大于它的数字整除。 Here's my solution:这是我的解决方案:

function sumPrimes(num){
    var sum = num>=2?2:0;
    for(var i=3;i<=num;i+=2){
        var isPrime=true;
        for(var j=3;j<(i/2);j++){
            if (i%j==0)
            {
                isPrime=false;
                break;
            }
        }
        sum+=isPrime?i:0;
    }
    return sum;
}

Note: I started from j=2 because we are only checking odd numbers, so they'd never be divisible by 2.注意:我从 j=2 开始,因为我们只检查奇数,所以它们永远不会被 2 整除。

function sumPrimes(num) {
  var sumArr= [];
  for(var i=0;i<=num;i++){
    if(isPrime(i))
      sumArr.push(i);
  }

  sumArr = sumArr.reduce(function(a,b){
    return a+b;
  })

  return sumArr;
}

function isPrime(num) {
    if(num < 2) return false;
    for (var i = 2; i < num; i++) {
        if(num%i === 0)
            return false;
    }
    return true;
}

sumPrimes(10);

something like this?像这样的东西?

 function isPrime(_num) { for(var i = 2; i < _num; i++) { if(!(_num % i)) { return false } } return true; } function sumPrimes(_num) { var sum = 0; for(var i = 2; i <= _num; i++) { if(isPrime(i)) { sum += i; } } return sum; } sumPrimes(20) // 77 sumPrimes(5) // 10

You could do this as well.你也可以这样做。

 function sumPrimes(num) { var sum = 0; for (var i = 0; i <= num; i++) { if (isPrime(i)) { sum += i; } } return sum; } function isPrime(n) { if (n < 2) { return false; } if (n !== Math.round(n)) { return false; } var result = true; for (var i = 2; i <= Math.sqrt(n); i++) { if (n % i === 0) { result = false; } } return result; }

Here's my solution.这是我的解决方案。 I hope you find it easy to interpret:我希望你觉得它很容易解释:

function sumPrimes(num) {

  // determine if a number is prime
  function isPrime(n) {
    if (n === 2) return true;
    if (n === 3) return true;
    if (n % 2 === 0) return false;
    if (n % 3 === 0) return false;

    var  i = 5;
    var  w = 2;
    while (i * i <= n) {
        if (n % i === 0) {
            return false;
        }
        i += w;
        w = 6 - w;
    }
    return true;
  }

  // subtract 1 for 'not being prime' in my context
  var sum = isPrime(num) ? num - 1 : -1;

  for (var x = 0; x < num; x++) {
    if (isPrime(x) === true) {
      sum += x;
    }
  }

  return sum;
}

here is my solution to sum of n prime number这是我对 n 个素数之和的解决方案

 function sumOfNPrimeNumber(num){ var sum = 0; const isPrime = function(n){ if (isNaN(n) || !isFinite(n) || n%1 || n<2) { return false; } if (n%2==0){ return (n==2); } var sqrt = Math.sqrt(n); for (var i = 3; i < sqrt; i+=2) { if(n%i == 0){ return false; } } return true; } const getNextPrime = function* (){ let nextNumber = 2; while(true){ if(isPrime(nextNumber)){ yield nextNumber; } ++nextNumber; } } const nextPrime = getNextPrime(); for (var i = 0; i < num; i++) { sum = sum + nextPrime.next().value; } return sum; } console.log(sumOfNPrimeNumber(3));

All the above answers make use of helper functions or aren't time efficients.以上所有答案都使用了辅助函数或不是时间效率。 This is a quick, recursive solution in O(n) time:这是O(n)时间内的快速递归解决方案:

// @ signature int -> int
// @ interpr: returns sum of all prime integers <= num
// assume: num is positive integer

function sumPrimes(num) {
  if (num <= 2) {
    return 2;
  }

  let i = 2;
  while (i < num) {
    if (num % i === 0) {
      return sumPrimes(num - 1)
    }
    i++;
  }
  
  return num + sumPrimes(num - 1)
}

// test
sumPrimes(10); // -> 17

The following solution uses the Eratosthenes Sieve to sum all prime numbers lower than or equal to num .以下解决方案使用Eratosthenes Sieve对所有小于或等于num素数求和。 The first for loop fills an array with size equal to num with true .第一个 for 循环用true填充大小等于num的数组。 The second for loop sets to false all non-prime numbers in the array .第二个 for 循环将array中的所有非质数设置为false Then, the last for loop simply iterates through the array to sum all the array indexes i for which the value in the array, ie, array[i] , is equal to true .然后,最后一个 for 循环简单地遍历array以求和所有数组索引i ,其中数组中的值即array[i]等于true

/**
 * Sum all primes lower or equal than n.
 * Uses the Eratosthenes Sieve to find all primes under n.
 */
function sumPrimes(num) {
  let array = [];
  let output = 0;

  // Fill an array of boolean with 'true' from 2 to n.
  for (let i = 0; i <= num; i++) {
    array.push(true);
  }

  // Set all multiples of primes to 'false' in the array.
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (array[i]) {
      for (let j = i * i; j <= num; j += i) {
        array[j] = false;
      }
    }
  }

  // All array[i] set to 'true' are primes, so we just need to add them all.
  for (var i = 2; i <= num; i++) {
    if (array[i]) {
      output += i;
    }
  }

  return output;
}

console.log(sumPrimes(10)); // 17
console.log(sumPrimes(977)); // 73156
console.log(sumPrimes(250_000_000)); // 197558914577

This is what I've done to get primes.这就是我为获得素数所做的工作。 I don't know if it's the most efficient, but it works.我不知道它是否最有效,但它有效。 This is in Java, but can be easily converted to JavaScript.这是在 Java 中,但可以轻松转换为 JavaScript。 Hopefully this will help point you in the right direction.希望这能帮助您指明正确的方向。

final int TOTAL = 10;
int primes[] = new int[TOTAL];
int arrPos = 2;
boolean prime = false;
primes[0] = 2;

for (int i = 2; i < TOTAL; i++) {
  prime = false;
  int sqrt = (int) Math.sqrt(i);
  for (int j = 1; j < arrPos && primes[j] < sqrt; j++) {
    if (i % primes[j] != 0) {
      prime = true;
    } else {
      prime = false;
      break;
    }
  }

  if (prime == true) {
    primes[arrPos] = i;
    arrPos++;
  }
}
function prime_sum(num){
let count=0;        *//tracks the no of times number is divided perfectly*
   for(let i=1;i<=num;i++){        *//from 1 upto the number*
      if(num%i==0){count++};
}
if(count===2){return "Prime"};
return{"Not prime"};
}
console.log(prime_sum(10));//expected output is 17**

//the code receives a number,checks through the range and returns prime if it meets the condition //代码接收一个数字,检查范围,如果满足条件则返回素数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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