<script> var countPrimes = function(n) { let flagArray = [], result = 0; for(let i = 2; i < n; i++){ if(flagArray[i] === undefined){ flagArray[i] = 1; result++; let j = 2; while(i * j < n){// 将以后与当前值能整除的排除掉 flagArray[i * j] = 0; j++; } } } return result;};console.log(countPrimes(10));console.log(countPrimes(100));</script>
可得如下运行结果:
附:这里再补充一个JS计算给定范围内素数的算法示例
<script>function PrimesList(m,n){ var rel = []; for (var i = m; i < n ; i++) { for (var j = 2; j < i; j++) { if (i%j==0) { break; } else{ rel.push(i); } } } return rel}console.log(PrimesList(100,200));</script>