finding sum of prime numbers under 250

2020-02-12 21:45发布

var sum = 0

for (i = 0; i < 250; i++) {

    function checkIfPrime() {

        for (factor = 2; factor < i; factor++) {
            if (i % factor = 0) {
                sum = sum;
            }
            else {
                sum += factor;
            }
        }
    }
}

document.write(sum);

I am trying to check for the sum of all the prime numbers under 250. I am getting an error saying that i is invalid in the statement if (i % factor = 0) I know was creating in the original for statement, but is there any way to reference it in the if statement?

8条回答
劫难
2楼-- · 2020-02-12 22:03

Here is a simple way of looping through array and implementing the sieve of Eratosthenes...

function sumPrimes(num) {
  var t, v = [],
    w = [],
    x = [],
    y = [],
    z = 0;
  //enumerating Vee array starts at 2 as first prime number
  for (let a = 2; a <= num; a++) {
    v.push(a)
  }
  //creating a moving loop by splicing its first index
  for (let i = 0; i < v.length; i) { //ensure all items spliced 
    t = v[i]; // t as prime to be removed from Vee array 
    x.push(t); // x storage of primes
    z += t //  total of peculiar primes
    w.push(v.splice(i, 1)) //tested to move all one by one
    // prompt(v) //tested that v loses its v[i] every iteration
    //= now trying to remove others using remainder (%) vs prime t
    for (let vi in v) {
      v[vi] % t === 0 ? y.push(v.splice(vi, 1)) : ""; //recursive removal of composite items by prime t
    }
  }
  return z // returns sum of primes
}
sumPrimes(250);

You generate the array beginning with 2 as first prime, You sieve the array removing items by the remainder of prime using % === 0. The you loop through the remaining array by using the next prime until the last remaining prime is pushed to the prime arrays. Add all primes to get the Sum.

查看更多
劫难
3楼-- · 2020-02-12 22:06
function sumPrimes(num) {
  var allprimes=[];
  for(i=2;i<=num;i++){
       var notPrime = true;
        for(j=2 ;j<=i;j++){
            if(i%j===0 && i!==j){
                notPrime = false;
            }
          }

    if(notPrime === true){
        allprimes.push(i);
    }
  }

  var addPrimes = allprimes.reduce(function(a,b){
     return a+b;
  });

  console.log(addPrimes);
}

sumPrimes(250);

You can equally use this;

查看更多
冷血范
4楼-- · 2020-02-12 22:08

With the prime computation, have you considered using Sieve of Eratosthenes? This is a much more elegant way of determining primes, and, summing the result is simple.

var sieve = new Array();
var maxcount = 250;
var maxsieve = 10000;

// Build the Sieve, marking all numbers as possible prime.
for (var i = 2; i < maxsieve; i++)
    sieve[i] = 1;

// Use the Sieve to find primes and count them as they are found.
var primes = [ ];
var sum = 0;
for (var prime = 2; prime < maxsieve && primes.length < maxcount; prime++)
{
    if (!sieve[prime]) continue;
    primes.push(prime); // found a prime, save it
    sum += prime;
    for (var i = prime * 2; i < maxsieve; i += prime)
        sieve[i] = 0; // mark all multiples as non prime
}

document.getElementById("result").value =
      "primes: " + primes.join(" ") + "\n"
    + "count: " + primes.length + "\n"
    + "sum: " + sum + "\n";
#result {
    width:100%;
    height:180px
}
<textarea id="result">
</textarea>

(EDIT) With the updated algorithm, there are now two max involved:

  • maxcount is the maximum number of prime numbers you wish to find
  • maxsieve is a guess of sieve large enough to contain maxcount primes

You will have to validate this by actually checking the real count since there are two terminating conditions (1) we hit the limit of our sieve and cannot find any more primes, or (2) we actually found what we're looking for.

If you were to increase the number to numbers much greater than 250, than the Sieve no longer becomes viable as it would be consume great deals of memory. Anyhow, I think this all makes sense right? You really need to play with the Sieve yourself at this point than rely on my interpretation of it.

查看更多
淡お忘
5楼-- · 2020-02-12 22:11

So i had to face a similar challenge and here is my solution, i hope you find it helpful:

 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;
    }
查看更多
戒情不戒烟
6楼-- · 2020-02-12 22:14

Here's a pretty decent way to do it. It's not as advanced as the sieve but it's a decent starting point. NOTE: I'm using ES6 syntax.

 /*
 * Sum the first n prime numbers
 *
 * @param n (integer)
 * @return integer 
 *
 */
function sumNprimes(n){
  const arr = [];
  let i = 2

  while (arr.length < n) {
    if (isPrime(i)) {
      arr.push(i)
    }
    i++
  } 
  return arr.reduce( (x,y) => x+y );

  /*
  * @param n (integer)
  * @return Boolean
  *
  */
  function isPrime(n) {

    if ( n < 2 ) {
      return false
    }

    for ( let i = 2; i <= Math.sqrt(n); i++ ) {
      if ( n % i === 0 ) {
          return false;
      } 
    }
    return true
  }

}
查看更多
乱世女痞
7楼-- · 2020-02-12 22:16

i % factor === 0

Use === for comparison. = is for assignment. Yeah I said triple equals. Type coercion is annoying.

查看更多
登录 后发表回答