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;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s