在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP