# 找质数算法（Sieve of Eratosthenes筛法）

//找出n以内质数
void Sieve(int n)
{
bool[] a = new bool[n+1];
for (int i = 2; i <= n; i++)  a[i] = true;
for (int i = 2; i <= Math.Sqrt(n); i++)
{
if (a[i])
for (int j = i; j*i <= n; j++) a[j * i] = false;
}
for (int i = 0; i <= n; i++)
{
if (a[i])
Console.Write("{0},",i.ToString());
}
}

/**
* Solves the challenge by utilizing a Sieve of Eratosthenes (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
*
* @param options
* @returns {number}
*/
getSolutionViaSieve = function (options) {
var upperBound = options.upperBound || 0,
primes = new Array(upperBound),
primeSum = 0;

// Initialize all of the numbers from zero to upper bound with a null value.  Later, each index will be checked
// for null to see if it's been market yet.
for (var a=0; a<upperBound; a++) {
primes[a] = null;
}

// Iterate from the lowest prime (2) to upperBound to flag prime or not prime.
for (var i=2; i<upperBound; i++) {

// Only proceed if the current index hasn't been flagged as prime or not prime.
if (primes[i] === null) {

// Flag the current index as prime.
primes[i] = true;

// And flag any remaining multiples of this prime as not prime.
for (var j=i*i; j<upperBound; j+=i) {
primes[j] = false;
}
}
}

// Iterate and add up all primes.
for (var p=0; p<upperBound; p++) {
if (primes[p] === true) {
primeSum += p;
}
}

return primeSum;
};

console.log(getSolutionViaSieve({upperBound: 10}));
console.log(getSolutionViaSieve({upperBound: 2000000}));

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120