Nick G.
Nick G.

Reputation: 1175

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

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.

Upvotes: 2

Views: 453

Answers (4)

s1lence
s1lence

Reputation: 2188

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.

Upvotes: 2

jahroy
jahroy

Reputation: 22692

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.

Upvotes: 2

jackcogdill
jackcogdill

Reputation: 5122

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.

Upvotes: 1

user166390
user166390

Reputation:

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
}

Upvotes: 1

Related Questions