列出所有素数直到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 ]