简体   繁体   中英

if conditional when finding prime number - always returning false

var enteredValue = prompt("enter a number");
enteredValue = enteredValue + 0;
console.log(isPrime(enteredValue));

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

Can anyone tell me what I'm doing wrong? The code is always returning false.

You need to move the return of true out side of the loop, because you need to check all factors before returning true .

 var enteredValue = +prompt("enter a number"); console.log(isPrime(enteredValue)); function isPrime(num) { for (var i = 2; i < num; i++) { if (num % i === 0) { return false; } } return true; } 

Your method should return true outside of your for loop. With your example you are retuening in first iteratin, by entering else block.

This will work:

function isPrime(num) {
   for (var i = 2; i < num; i++) {
     if (num % i === 0) {
       return false; // return if  it's not a prime
     }
   }
   return true; // return only if it's a prime number
}

You can also check other prime solutions in this post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM