Check for Prime Number in Optimized way | Interview Question

Please find below logic which will help you to write most optimized way to find if a number is Prime or not.

What is Prime Number ?

A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).

BEST Coding Practice

It’s always preferable as Best Coding Practice to write a method instead of writing anywhere in the Class to create a reusable code.

boolean isPrime(int num)
{
       if ( n % 2 == 0 ) return false;

       for ( int i=3;  i*i < n,  i += 2)
       {
            if ( n % i == 0 ) 
                  return false;
       }
       return true;
}

 

Leave a Reply