Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...