### In this article, we will write a program to check if a number is prime or not.

### Prime Number

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

For example, 2, 3,5,7,11,13,… are prime numbers since they are only divisible by 1 and themselves.

4 is not prime since it has 3 divisors.. 1, 2 and 4

6 is not prime since it has 4 divisors… 1,2,3 and 6

Number 1 is not prime since it only has one divisor.. 1 itself.

### Java program for Prime Number

This Java Program checks whether the Given Number is a Prime number or not.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | package com.javatutorial; import java.util.Scanner; public class ExamplePrimeOrNot { public static void main(String[] args) { System.out.println("Please enter a number: "); Scanner reader = new Scanner(System.in); int num = reader.nextInt(); checkPrimeorNot(num); } private static void checkPrimeorNot(int n) { int j = 0; if(n==1){ System.out.println("1 is not prime"); return; } // We don;t need to go further than n/2 to check if n is prime for (int i = 2; i <= n/2; i++) { if (n % i == 0) { System.out.println("Number: " + n + " is Not Prime."); System.out.println("One of the factors is "+ i); return; } } System.out.println("Number: " + n + " is Prime. "); } } |

### Result :

Please enter a number:

91

Number: 91 is Not Prime.

One of the factors is 7

Please enter a number:

241

Number: 241 is Prime.

#### Reference

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

#

How to check prime numbers in the range of 100 using 2d array which fill random if user enter 5 then program will make matrix 5×5 and fill random numbers range of random numbers are 10 t0 100 and how we find prime numbers in the filling matrix

#

you don’t have to check numbers up to n/2. Square root of ‘n’ would be enough.

(…)

for (int i = 2; i <= sqrt(n); i++)

(…)

#

i <= 9?

#