×

Prime Number Program in Java

Prime Number Program in Java using for loop

A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In other words, a number which is divisible by itself and 1 is called the prime number. For example, 2, 3, 5, 7, 11, 17, 97, 109, 139, 173, 199, 1151, 1289, 1367, etc. Remember that 2 is an even number which is also a prime number.

In this section, we will create a prime number program in Java by using different logics. Also, create a Java program to find the prime number between the two given numbers.

Let’s write a Java program to check the given number is prime or not.

Filename: PrimeNumberExample.java

public class PrimeNumberExample
{             
public static void main(String[] args)
{
               int n = 5; // The number stored in ‘n’ will be checked for prime
               int countFactors = 0; // count factors of the number ‘n’
               if(n <= 1 ) // A prime number can never become less than 1
                               System.out.println(n + " is not the prime number");
               else
               {
                              for(int i = 2; i <= Math.sqrt(n); i++)
                              {
                                             if(n%i == 0)
                                                             countFactors++;
                                              if(countFactors > 0)
                                              {
                                                             System.out.println(n + " is not the prime number");
                                                             break; // breaks the loop if no factor is found
                                             }
                              }
                              if(countFactors == 0)
                                              System.out.println(n + " is the prime number");
               }
}
}

Output:

5 is the prime number

Explanation: In the above program, we are trying to find a factor, excepting 1 and the number itself, of the given number. If we are unable to get any factor, the given number is a prime number; otherwise, it is not a prime number.

Let’s create an other Java program to check the number is prime or not.

Filename: PrimeNumberExample1.java

public class PrimeNumberExample1
{
static void isPrime(int n)
{
               int countFactors = 0;
               if(n <= 1)
               {             
                               System.out.println(n + " is not the prime number");
                               return;
               }
               for(int i = 2; i <= Math.sqrt(n); i++)
               {
                               if(n%i == 0)
                                              //increments the countFactors by 1
                                              countFactors++;
                               if(countFactors > 0)
                               {
                                              System.out.println(n + " is not the prime number");
                                              break; // A factor is found, no need to check further.
                               }
               }
               if(countFactors == 0)
                               System.out.println(n + " is the prime number");                       
}
public static void main(String[] args)
{
               isPrime(2);
               isPrime(3);
               isPrime(10);
               isPrime(17);                        
}
}

Output:

2 is the prime number
3 is the prime number
10 is not the prime number
17 is the prime number

Find Prime Numbers Between Two Given Numbers

We can even find prime numbers between the two given numbers. The demonstration is given below.

Filename: PrimeNumberExample2.java

public class PrimeNumberExample2
{
static boolean isPrime(int n)
{
               int countFactors = 0;
               if(n <= 1)
                               return false;
               for(int i = 2; i <= Math.sqrt(n); i++)
               {
                               if(n%i == 0)
                                              countFactors++;
                               if(countFactors > 0)
                                              return false;
               }
               return true;         
}
public static void main(String[] args)
{
               int firstNumber = 1, secondNumber = 20;
               for(int i = firstNumber; i <= secondNumber; i++)
               {
                               if(isPrime(i))
                               System.out.println(i + " is the prime number");
               }                            
}
}

Output:

2 is the prime number
3 is the prime number
5 is the prime number
7 is the prime number
11 is the prime number
13 is the prime number
17 is the prime number
19 is the prime number

Related Topics

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.