Monday, September 21, 2015

Primality test and make a list of the prime numbers

public class PrimeNum {
    final static int MIN = 100, MAX = 500; /*Enter the max integer and the minimum integer here*/

    //Primarity test on x
    static boolean isPrimeNum( int x ) {
        if( x == 2 ) return true;
        if( x < 2 || x % 2 == 0 ) return false;
        for( int n = 3; n <= Math.sqrt((double)x); n += 2 )
            if( x % n == 0 ) return false;
        return true;
    }
    public static void main( String[] args ) {
        int cnt = 0;

        System.out.println( Prime numbers between "MIN+" and "+MAX );
        for( int n = MIN; n <= MAX; n++  ) {
            if( isPrimeNum( n ) ) {
                System.out.print( n + " " );
                if( ++cnt%5==0 ) System.out.println();
            }
        }
    }
}