Number prime test in JavaScript

I’m trying to complete the Codewars challenge that asks you to check if a number is a prime number. For whatever reason, my solution doesn’t seem to work for the square of odd prime numbers (e.g. 9 returns true instead of false).

function isPrime(num) {

  if (num === 2) {
    return true;
  } else if (num > 1) {
    for (var i = 2; i < num; i++) {

      if (num % i !== 0) {
        return true;
      } else if (num === i * i) {
        return false
      } else {
        return false;
      }
    }
  } else {
    return false;
  }

}

console.log(isPrime(121));

P.s. I included that second else/if statement because I was trying to solve the problem.

Answer

As simple as possible:

function isPrime(num) {
  for(var i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}

With the ES6 syntax:

const isPrime = num => {
  for(let i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}

You can also decrease the complexity of the algorithm from O(n) to O(sqrt(n)) if you run the loop until square root of a number:

const isPrime = num => {
    for(let i = 2, s = Math.sqrt(num); i <= s; i++)
        if(num % i === 0) return false; 
    return num > 1;
}

Leave a Reply

Your email address will not be published. Required fields are marked *