×

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

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.