范围内素数 - JavaScript


我们需要编写一个 JavaScript 函数,其中输入两个数字(比如 a 和 b),并返回 a 和 b 之间的质数总数(包括 a 和 b,如果它们是质数)。

例如 −

If a = 2, and b = 21, the prime numbers between them are 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


更新日期: 15-Sep-2020

1 千次以上浏览

启动您的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.