【发布时间】:2017-01-05 19:35:19
【问题描述】:
所以我试图将这个伪代码从 Wikipedia 翻译成 Javascript:
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',所以外部循环只在 i = 2 时执行。一旦你的第二个内部循环完成,i 就大于 sqrt(10)现在 9.
-
不要在每次迭代时重新计算
Math.sqrt(num),这是一个昂贵的操作。
标签: javascript arrays for-loop scope sieve-of-eratosthenes