简体   繁体   English

如果有条件在找到素数时-始终返回false

[英]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. 代码始终返回false。

You need to move the return of true out side of the loop, because you need to check all factors before returning true . 您需要将true的返回true移到循环的外部,因为您需要在返回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. 您的方法应该在for循环之外返回true。 With your example you are retuening in first iteratin, by entering else block. 在您的示例中,您将通过输入else块来进行第一迭代。

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 . 您还可以在本文中查看其他主要解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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