เราจำเป็นต้องเขียนฟังก์ชัน 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