范围内的素数 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/4 15:40:17

我们需要编写一个 JavaScript 函数,该函数接受两个数字,例如 a 和 b,并返回 a 和 b 之间的素数总数(如果它们是素数,则包括 a 和 b)。

例如 −

如果 a = 2,且 b = 21,则它们之间的素数为 2、3、5、7、11、13、17、19

它们的数量为 8。我们的函数应该返回 8。

让我们来编写该函数的代码 −

示例

以下是代码 −

const isPrime = num => {
   let count = 2;
   while(count < (num / 2)+1){
      if(num % count !== 0){
         count++;
         continue;
      };
      return false;
   };
   return true;
};
const primeBetween = (a, b) => {
   let count = 0;
   for(let i = Math.min(a, b); i <= Math.max(a, b); i++){
      if(isPrime(i)){
         count++;
      };
   };
   return count;
};
console.log(primeBetween(2, 21));

输出

以下是控制台中的输出 −

8

相关文章


有用资源