尋找最接近一個數字的質數 - 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
廣告