The task is to implement a function to determine if a number is prime.
The boilerplate code
function isPrime(num) {
// your code here
}
If the number is less than or equal to 1, it's not prime.
if(num <= 1) return false;
The number 2 is the only even prime number.
if(num === 2) return true;
If the number is even and greater than 2, then it's not prime.
if(num % 2 === 0) return true;
For other numbers, divide by odd numbers starting from 3 up until the square root of the number (because if a number has a divisor, any number bigger than the square root will have a corresponding value lesser than the square root). If none of the checked numbers divide it evenly, then the number is prime.
const limit = Math.sqrt(num);
for(let i = 3; i <= limit; i++) {
if(num % i === 0) return false;
}
return true;
The final code
function isPrime(num) {
// your code here
if(num <= 1) return false;
if(num === 2) return true;
if(num % 2 === 0) return false;
const limit = Math.sqrt(num);
for(let i = 3; i <= limit; i++) {
if(num % i === 0) return false;
}
return true;
}
That's all folks!
Top comments (0)