在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP