在 JavaScript 中找到指定数字的最近质数


我们需要编写一个 JavaScript 函数,该函数接受一个数字并返回 n 之后出现的第一个质数。

例如:如果数字为 24,则输出应为 29。

因此,让我们为这个函数编写代码 −

示例

代码如下 −

const num = 24;
const isPrime = n => {
   if (n===1){
      return false;
   }else if(n === 2){
      return true;
   }else{
      for(let x = 2; x < n; x++){
         if(n % x === 0){
            return false;
         }
      }
      return true;
   };
};
const nearestPrime = num => {
   while(!isPrime(++num)){};
   return num;
};
console.log(nearestPrime(24));

输出

控制台中的输出为 −

29

更新日期:19-Oct-2020

188 次浏览

开启你的 职业生涯

通过完成本课程获得认证

开始学习
广告
© . All rights reserved.