Find number is prime or not
Prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers. To accomplish this we have to check the number is not divided by 2 upto the half of the number. For example, if the number is 7 then we have to check for 2 and 3. Here the number 7 is not divisible by 2 and 3 therefore it is prime number.
Note: 0 and 1 are not prime numbers. The 2 is the only even prime number because all the other even numbers can be divided by 2.
PROGRAM
class PrimeNum {
public static void main(String args[]) {
int n = Integer.parseInt(args[0]);
boolean flag = true;
// 0 and 1 are not prime numbers.
// The 2 is the only even prime number.
if(n < 2)
flag = false;
else
{
for(int i=2; i<=n/2; i++)
{
if(n % i == 0)
{
flag = false;
break;
}
flag = true;
}
}
if(flag == true)
System.out.println(n + " is a prime number");
else
System.out.println(n + " is not a prime number");
}
}
OUTPUT 1
C:\>javac PrimeNum.java C:\>java PrimeNum 12 12 is not a prime numberOUTPUT 2
C:\>javac PrimeNum.java C:\>java PrimeNum 11 11 is a prime number