Skip to content Skip to sidebar Skip to footer

What Is The Output Of This Condition In The Prime Function?

I found this code from another post and I'm trying to understand a part of this solution. The part I'm asking about is this particular function function isPrime(num) { for

Solution 1:

for ( var i = 2; i < num; i++ ) {
    console.log(`${num} % ${i} === ${num % i}`); // Extra line
    if ( num % i === 0 ) {
        return false;
    }
}

In this code, what the code is actually doing is it's going through every single number between 2 and num, assigning it to the variable i, and checking if num is divisible by i. If it is, then it'll return false.

The % function (called the modulo function), basically takes two numbers, and returns the first number's remainder when divided by the second number. So, for example:

5 % 2 // = 1, 5/2 = 2 with 1 left over
7 % 3 // = 1, 7/3 = 2 with 1 left over

If the remainder is 0, then obviously the first number is divisible by the second number, since there's nothing left over. So the line num % i === 0 is checking for divisibility, essentially - it's checking if num is divisible by i.

For example, when checking 5 (with the extra console.log line), this is what's outputted to the console:

5 % 2 === 1
5 % 3 === 2
5 % 4 === 1

And this is what's outputted with 6 as num:

6 % 2 === 0

(It's stopped, because false is returned.)


Solution 2:

The % operator is the modulus operator. It returns the remainder after division. So n % x will be zero any time n is evenly divisible by x. In this example it's testing whether the number is divisible by any of the previous numbers.

The line num % i === 0 returns true whenever num is evenly divisible by i


Solution 3:

It means that if the rest of division of num by i equal 0 then num is divided by a number other than 1 and itself, then it is not a prime nubmer so return false. ('%' mean modulo or rest of division)


Solution 4:

% is the modulus operator. x%y = x mod y = the remainder when x is divided by y. So 4%1=0, 4%3=1, and 4%4=0.

Therefore, x%y==0 is equivalent to "x is divisible by y". Therefore the loop is checking, for each number from 2 to num - 1, is num divisible by that number. For a prime number, the answer will always be no. So any case where num is divisible by i, it is definitely not prime. If num is not divisible by any number in the range, then it's prime.

Interesting side note: the loop doesn't have to go all the way to num-1 - it could stop at sqrt(num) (rounded), do you see why?


Post a Comment for "What Is The Output Of This Condition In The Prime Function?"