计算从2到n的质数
我们需要编写一个以数字(例如n)作为第一个也是唯一的参数的JavaScript函数。
然后,该函数应返回从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
热门推荐
10 祝老婆生日祝福语简短
11 姐姐女儿结婚祝福语简短
12 高考前祝福语简短字句
13 公司28 周年祝福语简短
14 婚礼祝福语简短精辟的
15 父亲祝福语大全简短语
16 上岸离职祝福语大全简短
17 冬至婆婆的祝福语简短
18 老爸生日暴富祝福语简短