In an earlier article, we discussed how to solve Dijkstra’s algorithm in java. Let us see how to find the number is prime or not and also code *java program for prime numbers*. Firstly, What is a prime number?

Contents

# Prime Number :

A prime number is a number is only divisible by 2 numbers. Prime numbers can be divisible by 1 and the number itself. Some of the prime numbers

Now we mark this number as prime numbers? Let’s take the number 11 – 11 is only divisible by 1 and the number itself which is 11. So we need to *divide the number from 2(1 will divide all numbers) to that number itself* and if no other divisor than the 1 and the number itself, it is a prime number.

In programming, we need to check the number(n) if it is divisible by any of the numbers from 2 to n-1. We have to loop through all the numbers within that range and check the condition. If we take the number as n and the looping variable as i, the condition will be

### **Temp=n%i;**

**Temp=n%i;**

If this temp is equal to zero then the number is not prime otherwise the number is prime. Let’s code this concept using java.

**Java program for Prime Numbers:**

/* * Program to check the numbre is Prime or Not * Coded by Aravind Naveen - www.geeks10.com */ import java.util.Scanner; public class primeRnot { public static void main(String[] args) { // GETTING THE INPUTS int n; boolean flag=true; System.out.print("Enter the number to be checked: "); Scanner sc=new Scanner(System.in); n=sc.nextInt(); sc.close(); //CONDITION TO CHECK PRIME NUMBER for(int i=2;i<=n/2;i++) //Check the condition untill value of i reaches n/2; { int temp=n%i; if(temp==0) { flag=false; break; //To immediately exit from the loop; } } if(flag) { System.out.println(n+ " is prime"); } else { System.out.println(n+" is not prime"); } } }

In this above program, we get the input from the user and store the input as ‘**n**‘. The **flag** is a boolean variable which is used to identify whether the number passed or failed the Prime number condition for every iteration.

**The output of this program will be:**

Use your favorite IDE to run this Program OR Just copy this code into notepad and save the file as primeRnot.java [Class name.java]. Then run this program using CMD. [Javac primeRnot.java and java primeRnot].

## Conclusion

So that’s done with **finding the number is prime or not using java.** Hope this article will help you to understand the concept of f**inding the number is prime or not**. If you are interested in programming do subscribe to our E-mail newsletter for all programming tutorials.