Java Program to Check Prime Number

What is a Prime Number?

A prime number is a number that is only divisible by 1 or itself. For example, 11 is only divisible by 1 or itself. Other Prime numbers 2, 3, 5, 7, 11, 13, 17….

Note: 0 and 1 are not prime numbers. 2 is the only even prime number.

Java Program to check whether number is prime or not

Program Logic:

  • We need to divide an input number, say 17 from values 2 to 17 and check the remainder. If remainder is 0 number is not prime.
  • No number is divisible by more than half of itself. So we need to loop through just numberToCheck/2 . If input is 17, half is 8.5 and the loop will iterate through values 2 to 8
  • If a numberToCheck is completely divisible by other number, flag isPrime is set to false and the loop is exited.
public class PrimenumberToCheckCheck {
 public static void main(String[] args) {
  int remainder;
  boolean isPrime=true;
  int numberToCheck=17; // Enter the numberToCheckber you want to check for prime
  //Loop to check whether the numberToCheckber is divisible any numberToCheckber other than 1 and itself
  for(int i=2;i<=numberToCheck/2;i++)
   //numberToCheckber is divided by itself
            System.out.println(numberToCheck+" Divided by "+ i + " gives a remainder "+remainder);
       //if remainder is 0 than numberToCheckber is not prime and break loop. Else continue the loop
  // Check value true or false, if isprime is true then numberToCheckber is prime otherwise not prime
     System.out.println(numberToCheck + " is a Prime numberToCheckber");
     System.out.println(numberToCheck + " is not a Prime numberToCheckber");

Expected Output:

17 Divided by 2 gives a remainder 1
17 Divided by 3 gives a remainder 2
17 Divided by 4 gives a remainder 1
17 Divided by 5 gives a remainder 2
17 Divided by 6 gives a remainder 5
17 Divided by 7 gives a remainder 3
17 Divided by 8 gives a remainder 1
17 is a Prime numberToCheckber

Check our program to Find Prime Numbers from 1 to 100