What does var prime = num != 1; mean?

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

I know this is similar to another SO question, but the variable prime is supposed to be any number other than 1, and it looks to me like it would be assigned the boolean value of num != 1. Can anyone tell me what this line of code is actually doing?

Here's the code where it's being used

function isPrime( num ) {    var prime = num != 1; // Everything but 1 can be prime    for ( var i = 2; i < num; i++ ) {      if ( num % i == 0 ) {        prime = false;        break;      }    }    return prime;  }  

EDIT: I assume that this line does something like this:

if( num != 1) {     prime = num; } 

But I still want to know why or how this line of code does this.

回答1:

As you were thinking correctly, the statement var prime = num != 1; assigns the result of the boolean expression (num != 1) to the variable prime. This special case is included in kind of every prime checking code because 1 itself is not a prime number.

Your algorithm could be even faster if you only checked for divisors up to the square root of the input value. You can read about this here and may notice that it's far more efficient to check if num > i*i than sqrt(num) > i.

Additionally the algorithm you have could still return wrong values if you feed it negative or zero values.



回答2:

In other words:

If num == 1, set prime to false and skip the loop.

Otherwise, enter the loop and use the standard logic to determine the value of prime.

This is done because the standard logic (inside the loop) will not work on the number 1.

Therefore, as pst says, you check for the edge case outside the loop.

This helps keep the logic clean inside the loop.


To make it more readable (and correct for all values) I would re-write it like this:

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

You could also exit the loop once i is greater than num / 2 to make it more efficient.



回答3:

1 is not a prime number

That is an edge-case check because for(i = 2;..) (below) "skips" 1: because the loop never runs, prime is only set once to false (which is the evaluation of i != 1, when i = 1).

However, I find it confusing and would have used:

if (i <= 1) {   return false; } else {   // other stuff } 


回答4:

The point of that line of code is to achieve two goals in one:

  • Firstly, they need to create a boolean variable
  • Second, they need to check if the number is 1, then it's not prime

They are just doing both at the same time.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!