素数最多为n-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 ]
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练