在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