# Prime Number or Not in Java Program

**Prime Number or Not in Java Program:**

**Logic:**

The number should not be divisible except its own and 1. Which means the given number’s Mod should not be zero (0) with any number.

So we have to put one loop to check whether any one of the number from 2 with the input given number’s Mod is zero, if then it is not a prime number, else its a prime number.

**Program:**

package in.javadomain; public class PrimeNumberOrNot { public static void main(String[] args) { int number = 83; boolean isPrime = true; int var = 2; while(var<number){ if(number%var==0){ System.out.println("Not a Prime Number"); isPrime = false; break; } var++; } if(isPrime){ System.out.println("Prime Number"); } } }

**Output:**

Prime Number

**Printing All Prime Numbers:**

The logic which we implemented above only we need to call as many times we need, say if we want to display the prime numbers which are under 100 then we need to call the above method 100 times.

package in.javadomain; public class PrintPrimeNumbers { public static void main(String[] args) { System.out.println("Prime Numbers are: "); for (int i = 1; i <= 20; i++) { boolean isPrime = isPrime(i); if (isPrime) { System.out.println(i); } } } private static boolean isPrime(int number) { boolean isPrimeNum = true; int var = 2; while (var < number) { if (number % var == 0) { isPrimeNum = false; break; } var++; } return isPrimeNum; } }

**Output:**

Prime Numbers are: 1 2 3 5 7 11 13 17 19

**Note:** If you want to display the prime numbers till 100 then change the above 20 in the for loop to 100.

**Recommended Books:**

446 total views, 1 views today