Task
Define a function that takes an integer argument and returns logical value true or falsedepending on if the integer is a prime.Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Example
is_prime(1) /* false */
is_prime(2) /* true */
is_prime(-1) /* false */
First Try
function isPrime(num) {
if (num < 2) {
return false;
}for (let i = 2; i < (num / 2) + 1; i++) {
if (num % i === 0) {
return false;
}
}return true;
}
It passed all test except for time complexity. My first solution is failed to execute time out though I limited loop for half (num / 2)
Final Answer
function isPrime(num) {
if (num < 2) {
return false;
}if (num === 2) {
return true;
}
const maximumDividor = Math.sqrt(num) + 1;for (let i = 2; i < maximumDividor; i++) {
if (num % i === 0) {
return false;
}
}return true;
}
I replaced the square root method instead of the half value. It will improve execute time half of the half.