在 JavaScript 中列出所有低于特定数字的素数
我们需要编写一个 JavaScript 函数,它接收一个数字(例如 n),并返回一个包含所有低于 n 的素数的数组。
例如:如果数字 n 为 24。
那么输出应该是 -
const output = [2, 3, 5, 7, 11, 13, 17, 19, 23];
那么,让我们为这个函数编写代码 -
示例
代码如下 -
const num = 24;
const isPrime = num => {
let count = 2;
while(count < (num / 2)+1){
if(num % count !== 0){
count++;
continue;
};
return false;
};
return true;
};
const primeUpto = num => {
if(num < 2){
return [];
};
const res = [2];
for(let i = 3; i <= num; i++){
if(!isPrime(i)){
continue;
};
res.push(i);
};
return res;
};
console.log(primeUpto(num));输出
在控制台中输出为 -
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP