Monday, September 21, 2015

Primality test

In this class, I am using "display()" method which displays whether the number is a prime number. Note that method is different from object though it seems similar a little.

----------------------------------------------------------------------------
class Test{
    public static void main(String args[]){
    display(44);
    display(5);
    display(46487);
    display(97247);
    }

   private static void display(int Num){
         if( isPrimeNum( Num ) ) {
            System.out.println( Num + " is a prime number." );
         } else{
            System.out.println( Num +" isn't a prime number.");
         }
      }

   private static boolean isPrimeNum( int x ) {
         if( x == 2 )
         return true;

         if( x < 2 || x % 2 == 0 )
         return false;

         for( int a = 3; a <= Math.sqrt((double)x); a += 2 )
             if( x % a == 0 )
             return false;
 
   return true;
   }
 }
----------------------------------------------------------------------------