Prime Number Program in Java



Prime number is a number which is divisible by itself.
We can write this program in multiple ways but it will reduce the performance for 
larger numbers. Here we define one of faster and optimised way to check if number is prime or not.



public boolean isPrime(int value) {
          if(value == 2)
                   return true;  
         if (value % 2 == 0)
                   return false;
         for (int j = 3; j <= Math.sqrt(value); j+=2) {
               if (value % j == 0) {
                       return false;
              }
        }
        return true;
}


In this function, we first check if number is divisible by 2 or not. If not then no need to check with any other even numbers, So in for loop we increment value by 2. We use sqrt(value) as upper limit as if value is multiple of two number like a and b, then one of this number will be always less than square root value. So by using sqrt as upper limit, we will reduce time to check if number is prime or not.




Comments

  1. This will output 2 as not being prime.... And i believe you posted the same code over stack overflow.. please rectify it

    ReplyDelete
    Replies
    1. Yes this will not. As this program was written to find prime number in lesser time keeping that in mind that 2 is prime number.
      I have updated program with your suggestion.

      Delete

Post a Comment

Popular posts from this blog

Disable or enable proxy for Internet explorer or Chrome

chm viewer unable to show contents

3 prisoners and 5 hats puzzle