CheetahBongos
CheetahBongos

Reputation: 197

Do not understand code to test if a number is prime or not

I found this code online. It is not my own. This is a function to test whether a given number is prime or not. The code works in determining whether a number is prime or not. I just don't understand how it works.

function test_prime(n)  
{  

  if (n===1)  
  {  
    return false;  
  }  
  else if(n === 2)  
  {  
    return true;  
  }else  
  {  
    for(var x = 2; x < n; x++)  
    {  
      if(n % x === 0)  
      {  
        return false;  
      }  
    }  
    return true;    
  }  
}  

alert(test_prime(25)); 

The first if and the else if statement make sense to me. If n is equal to 1 then return false being that 1 is not a prime number. else if n is equal to 2 then return true because 2 is a prime number.

Everything inside the else statement doesn't make sense to me. If you call the function testing for 25, which is not a prime number, 25%x, x=2, equals 1. Then why would the function return false?

I know there is something about the for loop I'm not understanding.

Upvotes: 2

Views: 989

Answers (3)

Shondeslitch
Shondeslitch

Reputation: 1079

   for(var x = 2; x < n; x++)  
    {  
      if(n % x === 0)  
      {  
        return false;  
      }  

}

I think you would look this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

The value of x is between 2 and n-1. While you are in loop, the value of x is changing: first x=1, then x=2, later x=3... when x=5 the condition is true and then return false.

Upvotes: 2

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

Explanation of else block

else  
  {  
    for(var x = 2; x < n; x++)  // Iterating over possible divisors i.e number - 1
    {  
      if(n % x === 0) // Checking whether the number is divisible by any number, if it is then return false i.e. number is not a prime number  
      {  
        return false;  
      }  
    }  
    // If the number is not divisible by any number return true
    return true;    
  }  

Upvotes: 2

Hunan Rostomyan
Hunan Rostomyan

Reputation: 2176

If n is neither 1 nor 2, then take the range of numbers between 2 and n and check if n is divisible by any of those numbers. If it is, then it's not prime, so you return false. If none of the numbers in the range divide n, then n must be prime.

Upvotes: 5

Related Questions