简体   繁体   中英

finding sum of prime numbers under 250

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?

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:

  • is the maximum number of prime numbers you wish to find 是您希望找到的最大素数数
  • is a guess of sieve large enough to contain primes 是对足够大的筛子的猜测,以包含素数

You will have to validate this by actually checking the real 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.来验证这一点,因为有两个终止条件 (1) 我们达到了筛子的极限并且找不到更多素数,或者 (2) 我们实际上找到了我们正在寻找的东西。

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.

You can equally use this

 let sum = 0; let num = 250; for (let i = 2; i < num; i++) { let isPrime = true; for (let j = 2; j < i; j++) { if (i % j === 0) { isPrime = false; } } if (isPrime) { sum += i; } } console.log(sum);

i % factor === 0

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

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
  }

}

你需要一个===== : if (i % factor == 0)

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

As per the " Sieve of Eratosthenes ", I have implemented the code using JS:

 function isPrime(n){ return ((n/2 === 1 || n/3 === 1 || n/5 === 1 || n/7 === 1)?true:(n%2===0 || n%3 === 0 || n%5 ===0 || n%7 === 0)?false:true); }; var val = 250; let outArr = []; for(let i=2;i<val;i++){ if(isPrime(i)){ outArr.push(i); } } console.log("Prime number between 0 - "+val+" : "+outArr.join(","));

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.

If the question is purely academical, earlier answers are better suited.

The example below uses modern libraries, in case you need an efficient solution.

import {generatePrimes} from 'primes-generator';
import {from, reduce, take} from 'rxjs';

from(generatePrimes())
    .pipe(take(250), reduce((a, c) => a + c))
    .subscribe(sum => {
        // sum = 182109
    });

Performance-wise, it will take significantly less than 1ms.


PS I am the author of primes-generator library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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