所以我想这个伪代码从Wikipedia翻译成JavaScript:JavaScript中的Eratosthenes筛选器?
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
这是据我得到:
function getPrimes(num) {
var a = [];
for (i=2;i<=num;i++){a.push(true);}
for (i=2;i<=Math.sqrt(num);i++){
for (var j=i*i, coef=0, l=i;j<num-2;coef++){
j = i*i+coef*l-2;
a[j]=false;
}
for (i=0;i<a.length;i++){
if (a[i]){a.splice(i,1,i+2);}
}
}
return a;
}
getPrimes(10); // returns [2, 3, false, 5, false, 7, false, 9, false]
// 9 should be false
因此,大家可以看到,该算法不捕获所有非素数。任何想法,我已经错过了?预先感谢任何想尝试它的人。
你增加“我”在内环,所以外环只有当i = 2时才执行。一旦你的第二个内循环完成,我现在的大于sqrt(10)9. – Jecoms
不要在每次迭代时重新计算'Math.sqrt(num)',这是一个昂贵的操作。 – Oriol