Home > OS >  isPrime function logs 15 as true (15 is not a prime number)
isPrime function logs 15 as true (15 is not a prime number)

Time:03-23

function isPrime(num){
  // loop numbers to see if any num is divisble by that number
  
  if (num < 2){ return false
    
  } else if (num === 2) {
    return true
  }
  
  for (let i = 2; i < num; i  ) {
    if (num % i === 0) {
      return false
    } else {
      return true
    }
}
}

Tried changing the conditional of the for loop but still comes out as true.

CodePudding user response:

Wait until the whole loop finishes before returning true, otherwise you only check the first iteration and make a decision right away whether the input is prime before checking all the rest of the numbers. Also surely you don't need to iterate the entire length of the number, Math.ceil(num/2) 1 should suffice. This is because there's no point to ever check if anything larger than half of a number will factor into that number. (This will make a big impact on larger numbers)

function checkPrime(){
    var num = document.getElementById("num").value;
    var result = document.getElementById("result");
    var arr=[];
    if (num.length===0)
        result.innerHTML = "Please, specify a number.";
    else if (num<0)
        result.innerHTML = "Please, specify a positive number.";
    else
        result.innerHTML = isPrime(num).toString();
        
    return false;
}

function isPrime(num){
  // loop numbers to see if any num is divisble by that number
  
  if (num < 2)
      return false;
  else if (num === 2)
    return true;
  
  const max = Math.ceil(num/2)   1;
  for (let i = 2; i < max; i  ) {
    if (num % i === 0)
      return false;
  }

  return true;
}
<form onsubmit=" return checkPrime()">
      <label>Enter a number check prime</label>
      <input type="number" id="num" name="num"><br>
      <input type="submit" value="Submit" id="submit">
      <div id="result"></div>
</form>

CodePudding user response:

This means you are testing any number entered to return a bool (true/false) if it is a prime number.

I would modify your code a little bit to give this function a correct answer.

function isPrime(num){
  // loop numbers to see if any num is divisble by that number
  
  if (num < 2){ 
      return false
  }else if(num==2){
      return true;
  }else{
      for (let i = 2; i < num; i  ) {
           if (num % i == 0) {
             return false;
             break;
            }
       }
      return true;
  }
  
}

  • Related