Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(" ") + "
"
    + "count: " + primes.length + "
"
    + "sum: " + sum + "
";
#result {
    width:100%;
    height:180px
}
<textarea id="result">
</textarea>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...