## What is prime number

A number is called as a prime if it has only two divisors. In other words, a number which is divided only by 1 and itself. i.e.; number of factors for a prime number should only be 2 (1 and itself).For example, 2 is a prime number since it has only two factors 1 and 2. 6 is not a prime number since it has 4 factors 1, 2, 3, and 6.

## Prime number program

I've developed a sample Java program to identify given number is prime number or not. Logic is very simple, for every number 1 and itself are the definite factors. So, we should count the factors of a given number from 2 to n-1. If we find any factory between 2 and n-1, then the given number is not a prime number**PrimeNumber.java**

import java.io.*;

/**

* This class demonstrates the prime number.

* @author SANTHOSH REDDY MANDADI

* @version 1.0

* @since 19 August 2012

*/

class PrimeNumber

{

public static void main(String args[]) throws Exception

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please enter a number:");

int number = Integer.parseInt(br.readLine());

if(isPrimeNumber(number))

{

System.out.println(number+" is a prime number.");

}

else

{

System.out.println(number+" is not a prime number.");

}

}

public static boolean isPrimeNumber(int number)

{

int i;

for(i=2; i< number; i++)

{

if(number%i == 0)

{

break;

}

}

if(i == number)

{

return true;

}

return false;

}

}

**Output**

>java PrimeNumberWe can even extend above program to display prime numbers list between 1 and given number. We can reuse the method isPrimeNumber here as well.

Please enter a number:

23

23 is a prime number.

>java PrimeNumber

Please enter a number:

6

6 is not a prime number.

**PrimeNumbers.java**

import java.io.*;

/**

* This class lists all prime number upto the given number.

* @author SANTHOSH REDDY MANDADI

* @version 1.0

* @since 19 August 2012

*/

class PrimeNumbers

{

public static void main(String args[]) throws Exception

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please enter a number:");

int number = Integer.parseInt(br.readLine());

System.out.println("List of prime numbers between 1 and "+number+": ");

int count = 0;

for(int i=2; i<=number;i++)

{

if(isPrimeNumber(i))

{

System.out.printf("%10d", i);

count++;

}

}

System.out.println("\n\nThere are "+count+" prime numbers between 1 and

"+number);

}

public static boolean isPrimeNumber(int number)

{

int i;

for(i=2; i< number; i++)

{

if(number%i == 0)

{

break;

}

}

if(i == number)

{

return true;

}

return false;

}

}

**Output**

> java PrimeNumbers

Please enter a number:

100

List of prime numbers between 1 and 100:

2 3 5 7 11 13 17 19

23 29 31 37 41 43 47 53

59 61 67 71 73 79 83 89

97

There are 25 prime numbers between 1 and 100