Java program to check prime number

Java Program to check prime number

We can write a java program to check a prime number or not by checking if the number is only divisible by 2 numbers. Either it is divisible by 1 or itself, it is a prime number. Hence, if a number is divisible by another number, it is not a prime number. For example, 3, 5, 7 etc are prime numbers are they are not divisible by any other number. We can check if a number is prime or not in many ways. Some of those ways are by using for loop, by using while loop, etc

Some facts about prime number are:

  • 2 is the only even number which is prime.
  • Every even number which is greater than 2 can be written as the sum of 2 prime numbers.
  • There are only 2 numbers which are prime and consecutive which are 2 and 3.

Java program to check prime number using for loop

public class DeveloperHelps {
public static void main(String[] args) {
int number = 13;
boolean flag = false;
for(int i = 2; i <= number/2; ++i) {
if(number % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(number + " is a prime number.");
else
System.out.println(number + " is not a prime number.");
}
}

The output of the program will be:

13 is a prime number. 

When we are checking inside for loop, we check if the number is divisible by any other number by dividing it by 2. If it is divisible, we get the output as true. As a result the number is not a prime number. As a result, the value is false and the number is a prime number.

We can also perform the same using while loop. Check out the below program for better understanding.

public class DeveloperHelps {
public static void main(String[] args) {
int number = 13, i = 2;
boolean flag = false;
while(i <= number/2)
{
if(number % i == 0)
{
flag = true;
break;
}
++i;
}
if (!flag)
System.out.println(number + " is a prime number.");
else
System.out.println(number + " is not a prime number.");
}
}

The output of the above program will be:

13 is a prime number.

In the while loop, the loop will run until i<= number/2. We will check if the number is divisible by i in each iteration. And the value of i will keep incrementing by 1.

Leave a comment

Your email address will not be published. Required fields are marked *