Prime Number in Java: How to Check for Primality and Generate Prime Numbers

Prime Number in Java: How to Check for Primality and Generate Prime Numbers

8 mins read707 Views Comment
Updated on Oct 3, 2023 11:43 IST

This article will aid knowledge in your programming journey to analyze Java’s primality and prime numbers.

2023_01_Prime-Number-in-Java-1.jpg

Java is one of the most popular programming languages for building mobile apps, games, websites and software. The code written in Java is the code that can be written once but can run anywhere. All those platforms that support Java can run the Java code except for any recompilation. Being concerned with the rules and syntax of Java, it is quite similar to c and c++ programming languages. 

Explore free C++ courses

Java is mainly described as a programming language that is based on the use of classes and objects. James Gosling was the developer of this object-oriented programming language, Java. From its release year 1995 to the present, it has upgraded many features as well.

Explore free Java courses 

With high performance, robustness, security, and portability, Java 19 is the preferable object-oriented programming language and more than 9 million developers use the latest version of Java worldwide. 

Before checking the primality in Java, one must install JDK as per their Windows, mac, or mobile uses. Before diving deep into prime numbers in Java, one must know the answers to such questions as primality and prime in Java.

Explore- Java Online Courses & Certifications

What are the Prime Numbers?

In mathematics, prime numbers can only be divisible by 1 and the number itself. For instance, 2 is the number that is divisible by 2 and 1 only. Between the counting numbers 1 to 100, there are 25 prime numbers. 

Every prime number is odd, but it is not valid in the case of 2. In the case of 2, it is the smallest odd and prime number. Writing a program of prime numbers in Java is simple; one has to use the loop in a way that will only return the prime number. 

Must read: Loops in Java Explained

Related Reads: Features of JAVA

Here are some examples of prime numbers.

2,3,5,7,11,13,17,19,23,29,31 etc.  

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
β‚Ή15 K
3 months
β‚Ή2.05 K
3 months
– / –
170 hours
β‚Ή5.4 K
1 month
– / –
6 months
– / –
2 months
β‚Ή17 K
3 months
β‚Ή5.5 K
1 month

What is Primality?

A test that aids in inspecting if a number is prime or not is renowned as a primality test. To check the primality of any number, one has to factorize it. Prime numbers are those which has only has only two factors, 1 and the number itself.

How can one Check Primality in Java?

With the help of classes and objects in Java, it becomes effortless to resolve any problem. Using two methods, it is easy to test the primality of any prime number in Java.

Method  

Step1. Divide that specific number up to half of the number itself

Step 2. Check if the reminder of this dividing process is greater than zero or not

Step 3. If the remainder is greater than zero, the given number is prime. 

Alternative Method 

Step1. Divide the number to be checked from 2 to its square root

Step 2. Check whether the remainder of this dividing process is greater than zero.

Step3. If the remainder exceeds zero, the given number is a prime number.

These methods will help us check any number’s primality in java programming. One can get the desired output to find the prime number by implementing this method with the java program.

How can one Generate Prime Number in Java?

To give rise to the prime numbers in Java, the loop is the best way to resolve it as it is the process of iterating numbers to check whether the number is prime or not. 

Each number is checked and increased by one in the loop at every iteration. With the aid of for and while loop, it becomes as easy as apple pie to generate the prime numbers in Java.

Program to Generate the Prime Number in Java using for Loop

Using for loop


 
public class Main {
public static void main(String[] args) {
// Check if 88 is a prime number
int number = 88;
boolean isPrime = isNumberPrime(number);
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
/**
* Returns true if the given number is a prime number, false otherwise.
*/
public static boolean isNumberPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Copy code

Output

88 is not a prime number.

Explore- Data Types in Java – Primitive and Non-Primitive Data Types Explained

Read More: For Loop in Java

Explanation 

  • In the above example, main method declares an integer variable called number and initializes it to 88.
  • We declare another boolean variable called isPrime and initializes it to the result of calling the isNumberPrime method with number as an argument.
  • Main method prints out either β€œ88 is a prime number.” or β€œ88 is not a prime number.” depending on the value of isPrime.
  • The isNumberPrime method takes an integer argument called number and returns a boolean value.
  • It checks if number is less than or equal to 1 and returns false if it is.
  • The isNumberPrime method then iterates over a range of integers from 2 to number / 2.
  • For each iteration, the method checks if number is divisible by the current integer. If it is, the method returns false.
  • If the loop completes without finding a divisor, the method returns true.

Program to Generate the Prime Number in Java using a While Loop

Using while loop


 
public class Main {
public static void main(String[] args) {
int n = 88;
boolean flag = false;
for(int i = 2; i <= n/2; ++i)
{
if(n % i == 0)
{
flag = true;
break;
}
}
if (!flag)
System.out.println(n + " is a prime number.");
else
System.out.println(n + " is not a prime number.");
}
}
Copy code

Output

88 is not a prime number.

Explanation 

  • In the above example, we are using the while loop to bring out the prime number, which is quite similar to the for a loop. The exact difference between for loop and the while loop is that in the for loop, the number of iterations is known, but in the case of the while loop, a condition is checked many times until it is proved wrong. 
  • In the above example, n is initialized as 19 and i as 2 in the expression of the while loop; when the expression is evaluated as true compiler jumps to the following line of code.
  • In line 7, when the if the condition evaluates as false due to (19%2==0), that is, when 19 is divided by 2 it gives the remainder of 1, which doesn’t satisfy the condition. The compiler directly moves to the if statement outside of the while loop.
  • Now the if statement runs the code (n + ” is a prime number.”); that is β€œ19 is a prime number”.
  • Output – 19 is a prime number.

Program to Generate the Prime Number in Java using Functions


 
public class Main{
static void checkPrimenum(int n1){
int i,m1=0,flag=0;
m1=n1/2;
if(n1==0||n1==1){
System.out.println(n1+" is not a prime number");
}
else{
for(i=2; i<=m1;i++){
if(n1%i==0)
{
System.out.println(n1+" is not a prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n1+" is a prime number");
}
}
}
public static void main(String args[]){
checkPrimenum(22);
checkPrimenum(7);
checkPrimenum(21);
checkPrimenum(60);
}
}
Copy code

Output

22 is not a prime number
7 is a prime number
21 is not a prime number
60 is not a prime number

Explanation 

  •  The above example uses Java methods to find if the entered number is prime.  
  • Numbers to be inspected as a prime are given as parameters to the method.
Difference between Abstract class and Interface in Java
The Key Difference Between C++ and Java
Difference between While and Do-While Loop

Program to Generate all the Prime Number in Java between Two Intervals


 
public class Main {
public static void main(String[] args) {
// Print all prime numbers between 30 and 60
for (int i = 30; i <= 60; i++) {
if (isNumberPrime(i)) {
System.out.print(i + " ");
}
}
}
/**
* Returns true if the given number is a prime number, false otherwise.
*/
public static boolean isNumberPrime(int number) {
// Check for negative numbers, 0, and 1
if (number <= 1) {
return false;
}
// Check for 2 and 3
if (number == 2 || number == 3) {
return true;
}
// Check for numbers divisible by 2 or 3
if (number % 2 == 0 || number % 3 == 0) {
return false;
}
// Check for all other prime numbers
int i = 5;
int max = (int) Math.sqrt(number);
while (i <= max) {
if (number % i == 0 || number % (i + 2) == 0) {
return false;
}
i += 6;
}
return true;
}
}
Copy code

Output

31 37 41 43 47 53 59 

Explanation 

  • In the above program, we define a class called PrimeNumbers that contains a method called main.
  • The main method prints all prime numbers between 30 and 60 to the console.
  • The main method uses a loop to iterate over a range of numbers and checks if each number is prime by calling a separate method called isNumberPrime.
  • The isNumberPrime method checks if a given number is prime by iterating over a range of integers and checking if the number is divisible by any of them. If the number is divisible by any of the integers, it is not prime. If the loop completes without finding a divisor, the number is prime.
  • After completing each iteration desired output is 31,37,41,43,47,53,59

Wrapping up

As an elementary student number system is the rough and ready red tip of mathematics. And prime numbers are part and parcel of an elementary school to a college-level student if you are in the programming stream. It is a basic-level program that is the essence of the matter to figure out by every java beginner. 

With the essentials of Java, such as object-oriented features and portability, it is entirely simple to generate prime numbers. I hope this article will ease your basic cognitive process of learning this fabulous programming language.

Contributed by Srashti

Blogs people also read in Java:

Data Type in Java | Features of Java Programming | Jump Statement in Java | OOPS in Java Java Interview Questions | Python vs Java | Conditional Statement in Java | Data Abstraction in Java | Super Keyword in Java | Method Overloading in Java | Difference between Java and Javascript | Constructors in Java | Method Overriding in Java Data Structure and Algorithm in Java | Abstract class in Java | Loops in Java

FAQs

Q1 What is the prime number?

Those numbers with only two factors that are 1 and the number itself are called prime numbers.

Q2 What is the Easiest way to find the prime number?

If a number has only two factors, 1 and the number itself, then it is a prime number. The factoring method is the easiest way to determine whether a number is a prime.

Q3 How many prime numbers are there between 1 to 100?

There are 25 prime numbers between 1 to 100.

Q4 What are the co-prime numbers? Answer- Two numbers become co-prime if they have H.C.F. 1 in common.

Two numbers become co-prime if they have H.C.F. 1 in common.

Q5 Is Java tough to learn?

Difficulty level of any programming language is based on the level of your understanding and how much you practice it; by practising, one can master this excellent language with ease.

Q6 Is Java a high-level or a low-level language? Answer- Java is a high-level language that programmers can easily understand and implement.

Java is a high-level language that programmers can easily understand and implement.

Q7 What are the features of Java?

Robust, object-oriented, platform-independent, secure, portable, and more.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio