计算从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 高考夸张祝福语大全简短
14 祝福语大全儿子结婚简短
15 教师新婚喜糖祝福语简短
16 新车新家祝福语大全简短
17 新婚男士祝福语大全简短
18 家庭聚餐的简短祝福语