在 JavaScript 中計算從 2 到 n 的所有質數
我們需要編寫一個 JavaScript 函式,它以一個數字(比如說 n)作為第一個且唯一引數。
然後,該函式應該返回從 2 到數字 n 之間所有質數的計數。
例如 −
For n = 10, the output should be: 4 (2, 3, 5, 7) For n = 1, the output should be: 0
示例
const countPrimesUpto = (num = 1) => { if (num < 3) { return 0; }; let arr = new Array(num).fill(1); for (let i = 2; i * i < num; i++) { if (!arr[i]) { continue; }; for (let j = i * i; j < num; j += i) { arr[j] = 0; }; }; return arr.reduce( (a,b) => b + a) - 2; }; console.log(countPrimesUpto(35)); console.log(countPrimesUpto(6)); console.log(countPrimesUpto(10));
輸出
控制檯中的輸出將如下 −
11 3 4
廣告