n 以内的素数 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/15 10:20:17

假设,我们需要编写一个 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
]

相关文章


有用资源