Home > Enterprise >  Probably a silly question regarding an isPrime function
Probably a silly question regarding an isPrime function

Time:04-14

My isPrime function for some reason does not work for multiples of 3.

console.log(isPrime(9)) returns me true, when the number is clearly not prime. I have been staring at the logic for a while and multiple google searches yield nothing, so I am assuming it is some really dumb oversight. I could probably copy and paste to make it work but I am attempting to build proper understanding.

function isPrime(num){
  for (let i = 2; i < Math.sqrt(num); i  ){
    if (num % i == 0){
      return false;
    }
    return true;
  }
}

console.log(isPrime(9)); 

CodePudding user response:

  1. i < needs to be replaced with i <=
  2. I added a variable to store the Math.sqrt call since that's an expensive operation to do every iteration.
  3. Your first iteration returns true or false immediately. You should remove the return true from the for loop completely to let it iterate.

function isPrime(num){
  let max = Math.sqrt(num);
  for (let i = 2; i <= max; i  ){
    if (num % i == 0){
      return false;
    }
  }
  return true;
}

console.log(isPrime(1));
console.log(isPrime(2));
console.log(isPrime(3));
console.log(isPrime(4));
console.log(isPrime(5));
console.log(isPrime(7));
console.log(isPrime(8));
console.log(isPrime(9));
console.log(isPrime(10));

CodePudding user response:

Instead of Math.sqrt you should write num.

  • Related