How to find the number is prime or not- Java program for prime numbers

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?

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

java program for 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;

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.

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 favourite 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].

java program for prime numbers-Output

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 finding the number is prime or not. If you are interested in programming do subscribe to our E-mail newsletter for all programming tutorials.