2

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.

  • 3
    The function doesn't return false in the case of n=25 for x=2. The loop will continue increasing x until x=5, at which point it will find that n is divisible by x and *then* return false. Note also that this function is pretty inefficient for its purpose. – Touffy Nov 28 '15 at 20:37
  • 2
    Duplicate of https://stackoverflow.com/questions/14650360/very-simple-prime-number-test-i-think-im-not-understanding-the-for-loop – Lil Devil Nov 28 '15 at 20:41

3 Answers3

5

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.

Hunan Rostomyan
  • 2,176
  • 2
  • 22
  • 31
  • Ahhhhh of course... the for loop code will run until x is 1 less than n... For some reason I thought that the for loop ended after the first run. Thanks! – CheetahBongos Nov 28 '15 at 20:48
2

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;    
  }  
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
2
   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.

Shondeslitch
  • 1,049
  • 1
  • 13
  • 26