Prime Number Program in Java

Prime numbers play a vital role in programming, especially in cryptography and algorithm design. Discover how to write and optimize a prime number program in Java, complete with easy-to-follow examples and key insights for efficient coding.

Have you ever been fascinated by the mysterious world of numbers? Prime numbers are significant in computer technology and mathematics. Any natural integer larger than one that can only be divided by one and itself is called a prime number. Prime numbers are essential for resolving challenging computing issues in algorithm optimization and cryptography.

In this blog, we will delve deeply into the idea of prime numbers and discover how to create several Java prime number applications. This blog will guide you on recognizing and operating with prime numbers, regardless of your level of experience as a developer. By the end, you will thoroughly understand various algorithms and how they are used in practical situations.

What are prime numbers?

Let’s first define prime numbers before moving on to the programming portion:

Prime Numbers: Any integer more significant than one that cannot be formed by multiplying two smaller natural numbers is referred to as a prime number. 

Example: 2,3,5,7,9,11,13 etc.

Non-Prime Numbers: these are also called composite numbers since they can be divided by themselves and numbers other than 1. 

Example: 4,6,8,9,10 etc.

Characteristics of Prime Numbers:

  1. The only even prime number and also the smallest prime number is 2.
  2. Every prime number larger than two is odd.
  3. There are precisely two distinct positive divisors of a prime number.
  4. Prime numbers are limitless, but they become less frequent as they get bigger.

Interesting fact: The most significant known prime number, as of 2023, is a Mersenne prime with over 24 million digits. Mersenne primes take the form 2^p – 1, where p is also a prime number. These numbers are used in advanced computing and cryptography.

Algorithm to Check for a Prime Number

To determine if a number is prime:

  1. A number less than 2 is not prime.
  2. Check the divisibility of the number from 2 up to the square root of the number.
  3. If the number is divisible by any number in this range, it is not a prime number.
  4. For large numbers, optimizations like skipping even numbers can save computation time.

Pseudocode

Function isPrime(n):
If n <= 1:
Return False
For i from 2 to √(n):
If n % i == 0:
Return False
Return True

This approach ensures efficiency, especially for large numbers, as we only check divisors up to the square root of the number.

The isPrime method in this example is declared as public, allowing it to be accessed from other classes. To learn more about how access modifiers work in Java, check out our guide on Access Modifiers in Java.

Writing a Simple Prime Number Program in Java

An introductory program to check if a number is prime:

import java.util.Scanner;
public class PrimeNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}

Explanation:

Input: The user enters a number.

Logic: The isPrime method checks divisibility up to the square root of the number.

Output: The program prints whether the number is prime or not.

Sample Input and Output:
Input: 7
Output: "7 is a prime number."
Input: 10
Output: "10 is not a prime number."

Are you not aware of data types in Java? This blog will help you learn Java data types!

Optimizing the Prime Number Algorithm

The above program works well, but it can be optimized further:

Key Optimizations

  1. Skip even numbers after checking 2, as all other even numbers are not prime.
  2. Start the loop from 3 and increment by 2 to reduce iterations.
  3. Advanced algorithms like the Sieve of Eratosthenes or probabilistic methods can be used for huge numbers.

Optimized Code

public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) return false;
}
return true;
}

This approach reduces the number of iterations in half for large numbers, making it faster than before.

Advanced Prime Number Programs

Here is a program to print all prime numbers in a range:

public class PrimeNumbersInRange {
public static void main(String[] args) {
int start = 10, end = 50;
System.out.println("Prime numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}

Output:

Prime Numbers in Range
Prime numbers between 10 and 50: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

Using Java’s collection framework, such as ArrayList, can simplify storing and manipulating prime numbers. Learn more about Collections in Java.

Program to Generate the First ‘N’ Prime Numbers:

public class FirstNPrimes {
public static void main(String[] args) {
int n = 10;
int count = 0, num = 2;
System.out.println("First " + n + " prime numbers:");
while (count < n) {
if (isPrime(num)) {
System.out.print(num + " ");
count++;
}
num++;
}
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}

Output:

For the given input (n = 10), the output will be:

First 10 prime numbers:
2 3 5 7 11 13 17 19 23 29

Real-World Applications of Prime Numbers in Programming

  • Cryptography: Public-key cryptosystems such as RSA use prime numbers.
  • Hashing Algorithms: Prime numbers in hashing algorithms ensure better hash function distribution.
  • Random Number Generation: To create pseudo-random sequences, algorithms frequently use prime integers.
  • Error Checking: Prime numbers are employed in checksums and cyclic redundancy checks (CRCs) to identify data transmission mistakes.

Learn more Java applications from our Free Java Applications Course where you can practically experiment with them too.

Testing and Debugging Tips:

  • Edge Cases: Always deal with negative values and numbers like 0 and 1.
  • Performance problems: Use optimized algorithms instead of naive approaches when dealing with big numbers.
  • Testing: To make sure your programs are proper, test them using a range of inputs.
  • Memory Considerations: Make sure to allocate enough memory for sophisticated algorithms such as the Sieve of Eratosthenes.

Conclusion

Prime numbers are the foundation of many practical applications; therefore, they are not merely an academic subject. In this blog, we looked at optimized algorithms, their usefulness, and how to create both basic and complex prime number programs in Java. We also discussed their practical applications, highlighting how crucial they are to computational mathematics and cryptography. 

By grasping these ideas, you are improving your Java proficiency and becoming ready for challenges in domains such as data science, cryptography, and competitive programming. Keep exploring, dive into more intricate algorithms and relish the learning process.

Want to learn Java in depth? take the help of our Free Java Programming Course.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top