Prime Number Program in Java: How to Print and Verify?
By Rohan Vats
Updated on Jul 02, 2025 | 33 min read | 46.47K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jul 02, 2025 | 33 min read | 46.47K+ views
Share:
Table of Contents
Did you know that 90% of the Fortune 500 companies are using Java as their go-to choice for software development in 2025? Implementing a prime number program in Java demonstrates Java’s efficiency in handling complex algorithms, showcasing why it remains essential for enterprise-grade applications and computational tasks.
A prime number program in Java prints and checks prime numbers using optimized algorithms that balance efficiency and computational complexity. Techniques like the square root check, 6k ± 1 method, and wheel factorization reduce redundant divisibility tests.
A prime number program in Java can be used in cryptography, where prime numbers are key to securing online communications. However, inefficient algorithms can lead to performance issues and security risks.
In this blog, you will explore how to print and check prime numbers using different methods of Java.
Want to sharpen your programming skills with industry-level proficiency in Java? upGrad’s Online Software Development Courses can equip you with tools and strategies to stay ahead. Enroll today!
Printing prime numbers from 1 to 100 involves iterating through a numeric range while applying conditional checks for divisibility. The prime number program in Java uses nested looping and boolean flags to determine primality efficiently for this range. Understanding this approach strengthens your grasp of fundamental algorithmic concepts, including conditional probabilities and loop control in Java.
If you want to learn essential programming skills to perform industry-relevant functions in Java, the following courses can help you succeed.
Code Example:
public class PrimeNumber {
public static void main(String[] args) {
for (int num = 2; num <= 100; num++) {
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num);
}
}
}
}
Output:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Output Explanation:
The output lists all prime numbers between 1 and 100. The program verifies each number’s primality by checking divisibility conditions and prints it when confirmed prime.
Use Case:
If you’re developing basic number theory applications, this method offers clear implementation insight. You can build on this to create more complex algorithms, such as prime factorization or cryptographic key generation.
Struggling to get a strong grip on Java programming? Explore upGrad’s Core Java Basics free course to build a solid foundation and kickstart your development journey today!
Now, let’s explore what are some of the prominent methods in Java to check and print prime number program in Java
Multiple algorithms exist in Java for checking and printing prime numbers, each balancing trade-offs between computational complexity and implementation clarity.
Selecting the appropriate method depends on input scale, performance requirements, and use case complexity, enabling tailored solutions from educational prototypes to high-performance cryptographic applications.
Let’s understand how you can use java program to print prime numbers using Brute-Force prime number program in Java.
The brute-force approach tests divisibility of a target number by all integers from 2 to n-1, verifying primality through exhaustive checks. This prime number program in Java implements nested looping and modulus operations to identify prime status, a foundational algorithm relevant across Java, JavaScript, ReactJS, and Node.js environments.
Code Example:
public class PrimeCheckBruteForce {
public static boolean isPrime(int n) {
if (n <= 1) {
return false; // 0, 1, and negatives are not prime
}
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int number = 17;
if (isPrime(number)) {
System.out.println(number + " is prime.");
} else {
System.out.println(number + " is not prime.");
}
}
}
Output:
17 is prime.
Output Explanation:
The function evaluates the number 17 by checking divisibility from 2 to 16. Since 17 has no divisors other than one and itself, the method returns true, prompting the output "17 is prime."
Time Complexity Analysis:
Java's brute-force prime number program operates in Java with O(n) time complexity, implying linear growth in divisibility checks proportional to the input size. This characteristic restricts its efficiency in large-scale scenarios but suits smaller inputs and educational purposes.
When to Use the Brute-Force Method?
You should apply this method when learning foundational programming concepts or running correctness tests on small numbers with minimal performance demands. Additionally, understanding this approach is beneficial before exploring optimized JavaScript, ReactJS, or Node.js algorithms.
Example Scenario
Suppose you’re developing a simple web application using ReactJS and want to validate user inputs as prime numbers before submission. Implementing this brute-force prime number program in Java can quickly help you prototype the backend logic. You can later translate this logic into JavaScript or Node.js for client-side or server-side validation.
Now’ let’s understand how you can print prime numbers in Java from 1 to 100 using the square root optimization method.
The square root optimization method enhances the prime number program in Java by limiting divisibility checks to values up to the square root of the candidate number. This reduces the number of iterations significantly, improving efficiency without sacrificing accuracy.
Code Example:
public class PrimeNumber {
public static void main(String[] args) {
for (int num = 2; num <= 100; num++) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num);
}
}
}
}
Output:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Output Explanation
The program prints all prime numbers between 2 and 100 by checking divisibility only up to the square root of each number. Non-primes such as 4, 6, and 9 are efficiently skipped due to early divisor detection within the optimized range.
Example Scenario
Let’s say you’re building a Node.js backend service that validates prime numbers submitted by users in an educational app. Using this square root optimized prime number program in Java as a reference, you can implement a performant, scalable algorithm in JavaScript to handle validation efficiently. This approach ensures responsive user experience even as the input size grows.
Time Complexity Analysis
The square root optimization lowers time complexity from O(n) to O(√n), significantly reducing the number of divisibility checks. This makes the prime number program in Java more efficient for larger inputs, balancing speed and simplicity. Early loop exits further decrease runtime by avoiding redundant calculations once a divisor is found.
When to use?
This method suits scenarios involving moderate to large numbers where brute-force becomes impractical.
If you want to learn advanced SQL functions for orgaizational Java applications, check out upGrad’s Advanced SQL: Functions and Formulas. The 11-hour free program will help you learn SQL, MySQL, and more.
Let’s explore how you can use Java program to print prime numbers from 1 to 100 using 6k ± 1 Prime Number Method
The 6k ± 1 prime number method optimizes primality testing by focusing only on candidates that fit a specific mathematical pattern. This pattern filters out multiples of 2 and 3 early, reducing the search space before applying detailed checks.
Code Example:
import java.util.ArrayList;
public class PrimeNumber6kMethod {
public static void main(String[] args) {
int n = 100; // Upper limit to find primes up to 100
ArrayList<Integer> primes = new ArrayList<>();
// Add the first three prime numbers explicitly
if (n >= 2) primes.add(2);
if (n >= 3) primes.add(3);
if (n >= 5) primes.add(5);
// Generate numbers using 6k ± 1 pattern and check for primality
for (int k = 1; 6 * k - 1 <= n || 6 * k + 1 <= n; k++) {
int num1 = 6 * k - 1; // 6k - 1
int num2 = 6 * k + 1; // 6k + 1
if (num1 <= n && isPrime(num1)) {
primes.add(num1);
}
if (num2 <= n && isPrime(num2)) {
primes.add(num2);
}
}
// Print the prime numbers
System.out.println("Prime numbers from 1 to " + n + ":");
for (int prime : primes) {
System.out.print(prime + " ");
}
}
// Helper method to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 == 0 || num % 3 == 0) return false;
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) return false;
}
return true;
}
}
Output:
Prime numbers from 1 to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Output Explanation:
The program lists prime numbers by generating candidates using the 6k ± 1 formula and verifying primality through an optimized isPrime() function. Composite numbers outside the pattern or failing divisibility tests are effectively excluded.
Time Complexity Analysis
Java's 6k ± 1 prime number program in Java reduces redundant checks by eliminating multiples of 2 and 3 upfront. The isPrime() helper maintains O(√n) complexity through square root divisibility testing, enhanced by early exits on factor detection.
When to use?
This method suits scenarios demanding more optimization than brute-force but less complexity than sieve algorithms. It’s well-suited for competitive programming, interview challenges, and numeric computations in languages like C++ and C#.
Example Scenario
Suppose you’re developing a cryptographic module in C++ that requires frequent prime number validations. Implementing the 6k ± 1 prime number program in Java logic from Java improves performance while maintaining accuracy. This ensures faster computations and resource efficiency, especially with larger prime ranges.
Now, let’s explore how you can use Java program to print prime numbers using the Arithmetic prime number method.
Arithmetic prime number methods leverage mathematical patterns and precomputation to identify primes efficiently. Unlike brute-force checking, these methods reduce unnecessary checks, enhancing performance, especially for large input ranges.
The Sieve of Eratosthenes is a classic arithmetic algorithm that uses boolean arrays to mark composite numbers, enabling fast prime enumeration, a concept analogous to precomputed indices in MySQL or tensor masking in PyTorch and TensorFlow for efficient computations.
Code Example:
import java.util.Arrays;
public class PrimeNumberArithmeticMethod {
public static void main(String[] args) {
int n = 100; // Upper limit
boolean[] isPrime = new boolean[n + 1];
// Step 1: Assume all numbers are prime initially
Arrays.fill(isPrime, true);
// Step 2: 0 and 1 are not prime numbers
isPrime[0] = false;
isPrime[1] = false;
// Step 3: Start marking multiples of primes
for (int p = 2; p * p <= n; p++) {
if (isPrime[p]) { // If p is prime, mark its multiples
for (int multiple = p * p; multiple <= n; multiple += p) {
isPrime[multiple] = false;
}
}
}
// Step 4: Print all prime numbers
System.out.println("Prime numbers from 1 to " + n + ":");
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
System.out.print(i + " ");
}
}
}
}
Output:
Prime numbers from 1 to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Output Explanation
The sieve program prints all prime numbers up to 100 by marking multiples of each prime as non-prime in a boolean array. This bulk elimination parallels tensor masking in deep learning frameworks, enhancing computational efficiency.
Time Complexity Analysis
Sieve of Eratosthenes runs in O(n log log n) time, outperforming trial division methods with O(n√n) complexity.
When to use?
This method generates large prime sets quickly and is favored in coding competitions and applications requiring frequent primality checks.
Example Scenario
Imagine you’re implementing a PyTorch model that requires efficient masking of prime-indexed features for selective computation. Using the Sieve of Eratosthenes prime number program in Java as a conceptual guide, you can generate prime masks efficiently. This enables optimized tensor operations and faster training times in deep learning pipelines.
Let’s understand how to print prime numbers in Java using the wheel factorization prime number method.
Wheel factorization enhances prime detection by systematically skipping multiples of small primes like 2, 3, 5, and 7. This method extends the 6k ± 1 approach to a larger cycle (e.g., 30k ± {1,7,11,13,17,19,23,29}), significantly reducing candidate numbers before primality tests.
Code Example:
import java.util.ArrayList;
import java.util.Arrays;
public class PrimeNumberWheelFactorization {
public static void main(String[] args) {
int n = 100; // Upper limit
ArrayList<Integer> primes = new ArrayList<>();
// Add the first few small primes explicitly
if (n >= 2) primes.add(2);
if (n >= 3) primes.add(3);
if (n >= 5) primes.add(5);
if (n >= 7) primes.add(7);
// Initialize boolean array for prime marking
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
// Eliminate multiples of known primes
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int multiple = i * i; multiple <= n; multiple += i) {
isPrime[multiple] = false;
}
}
}
// Wheel pattern offsets (30k ± offsets)
int[] wheel = {1, 7, 11, 13, 17, 19, 23, 29};
for (int k = 1; 30 * k <= n; k++) {
for (int offset : wheel) {
int candidate = 30 * k + offset;
if (candidate <= n && isPrime[candidate]) {
primes.add(candidate);
}
}
}
// Print primes
System.out.println("Prime numbers from 1 to " + n + ":");
for (int prime : primes) {
System.out.print(prime + " ");
}
}
}
Output:
Prime numbers from 1 to 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity Analysis
This method combines sieve techniques' O(n log log n) efficiency with O(√n) primality tests, resulting in a balanced and scalable algorithm. Its performance gains make it suitable for large input sizes without compromising accuracy.
When to use?
Use this method when generating prime numbers at scale, where traditional approaches become too slow. The algorithm’s filtering strategy also parallels resource optimization in containerized systems like Docker and Kubernetes, where eliminating redundant tasks improves throughput.
Example Scenario:
You can apply the Wheel Factorization prime number program in Java when handling large datasets requiring fast prime detection. This method is especially useful in cryptographic applications where quick, reliable prime generation is critical.
Now, let’s understand how to print prime numbers from 1 to 100 in Java using the count prime number program in Java.
The count prime number method in Java offers a straightforward way to detect prime numbers by counting their divisors. This technique checks each number’s divisibility count, printing it as prime if exactly two divisors exist, 1 and the number itself.
While simple, it lacks the efficiency of optimized methods like the square root or 6k ± 1 algorithms.
Code Example:
public class PrimeNumber {
public static void main(String[] args) {
for (int num = 2; num <= 100; num++) {
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
if (count == 2) {
System.out.println(num);
}
}
}
}
Output Example:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Output Explanation
The program prints all numbers between 2 and 100 with exactly two divisors, effectively listing primes. Composite numbers have more divisors and are automatically skipped, ensuring accuracy in a simple manner.
Time Complexity Analysis
The count prime number method employs nested loops resulting in quadratic time complexity, O(n²). This leads to a rapid increase in computations as input size grows, making it inefficient for large datasets. Despite this, its simplicity offers clear insight into basic divisibility checks, contrasting with more optimized algorithms.
Compared to O(√n) or O(n log log n) methods, the count method is significantly slower but remains instructive.
When to use?
This method suits scenarios with small input sizes or educational settings where understanding divisor concepts is more important than speed. It parallels straightforward validation logic in web development and Bootstrap forms, where clarity and simplicity often take precedence over performance optimization.
Example Scenario:
You might use the count prime number program in Java when teaching beginners about loops and conditionals, or during early-stage web development prototyping where simple, easy-to-follow logic is needed. This approach aligns with Bootstrap’s philosophy of clear, maintainable code, making it ideal for learning and small-scale applications.
Now, let’s take a closer look at how to find and print prime numbers in Java within a range.
Determining primality within a numeric range in Java involves diverse algorithmic strategies balancing computational complexity, memory usage, and implementation elegance. From straightforward iterative loops to recursive techniques, each method uses fundamental principles like divisibility and mathematical optimizations such as square root bounds to reduce redundant checks.
Let’s dive into different methods you can use to find prime numbers in Java and see how you can implement each one with simple loops or even recursion.
The for-loop method is one of the most straightforward ways to check whether a number is prime within a given range. You iterate over each number in the range and check whether it is divisible by any smaller numbers.
If it is not divisible by any number other than 1 and itself, it is prime.
This method uses a for loop to iterate through all numbers in the specified range.
Steps Followed
Example Code
public class PrimeInRange {
public static void main(String[] args) {
int start = 10; // Start of range
int end = 50; // End of range
System.out.println("Prime numbers between " + start + " and " + end + " are:");
for (int num = start; num <= end; num++) {
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime && num > 1) {
System.out.println(num);
}
}
}
}
Code Explanation
Use Case:
You can use the for-loop method when you require clear, iterative logic to check primality across a defined range, such as in educational projects. If your use case involves straightforward prime filtering in small data sets or scripting tasks, this method balances clarity with acceptable performance.
The while loop method works similarly to the for loop method but uses a while loop instead. This method is especially useful when you want more control over the loop conditions or don’t know the number of iterations in advance.
This approach uses a while loop to iterate through numbers in the specified range, checking each one for primality. The logic remains the same as that of the for-loop method, but here, the iteration and checks are performed using a while loop.
Steps Followed
Example Code
public class PrimeInRangeWhile {
public static void main(String[] args) {
int start = 10; // Start of range
int end = 50; // End of range
System.out.println("Prime numbers between " + start + " and " + end + " are:");
int num = start;
while (num <= end) {
boolean isPrime = true;
int i = 2;
while (i <= Math.sqrt(num)) {
if (num % i == 0) {
isPrime = false;
break;
}
i++;
}
if (isPrime && num > 1) {
System.out.println(num);
}
num++;
}
}
}
Code Explanation
Use Case:
This technique suits scenarios where input ranges are not predetermined, or you want fine-grained control over primality checks within event-driven or interactive Java applications. In performance-sensitive contexts, the while loop combined with square root optimization ensures efficient execution while maintaining readable, maintainable code.
Also Read: Do While Loop in Java: Syntax, Examples, and Practical Applications
Recursion is a more advanced technique for checking whether a number is prime. In recursion, a function calls itself to break down the problem into smaller, simpler subproblems. While recursion can be elegant, it might not always be the most efficient approach, especially for large ranges.
In this method, recursion checks whether a number is divisible by any number starting from 2, up to its square root.
The base case is simple:
While this approach offers an elegant solution, its major drawback is the overhead of recursive function calls, especially for large numbers. But for smaller ranges, it’s a clean and efficient way to demonstrate recursion.
Steps Followed
Example Code
public class PrimeRecursion {
public static void main(String[] args) {
int number = 29; // Example number
if (isPrime(number, 2)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
public static boolean isPrime(int number, int divisor) {
// Base case: If divisor exceeds square root of number, it is prime
if (divisor > Math.sqrt(number)) {
return true;
}
// If number is divisible by any divisor, it is not prime
if (number % divisor == 0) {
return false;
}
// Recursive call with the next divisor
return isPrime(number, divisor + 1);
}
}
Output:
29 is a prime number.
Why Does It Work?
Use case:
For example, a researcher working on a simulation involving complex number patterns or cryptographic algorithms might need to check prime numbers as part of the model's computation. Recursion would allow the researcher to break down the problem of finding primes into smaller, manageable tasks, making the code more elegant and modular.
While recursion may not be the most efficient for large datasets, it can be useful in models with smaller ranges or when simplicity and clarity are prioritized over performance.
When dealing with extremely large numbers, standard data types like int or long are not enough. Let's look into how you can efficiently check very large primes using BigInteger.
Java’s BigInteger class provides a robust solution for primality testing of very large integers beyond standard data type limits. Using its built-in isProbablePrime(int certainty) method, it employs advanced probabilistic algorithms like Miller-Rabin to efficiently determine primality with configurable confidence levels.
This approach is vital in high-performance computing and large-scale mathematical tasks, paralleling big number handling in scripting languages like BASH and PERL for system-level operations.
Code Example:
import java.math.BigInteger;
public class PrimeCheckBigInteger {
public static void main(String[] args) {
// Example 11-digit prime number
BigInteger bigNum = new BigInteger("32416190071");
if (bigNum.isProbablePrime(10)) {
System.out.println(bigNum + " is probably prime.");
} else {
System.out.println(bigNum + " is not prime.");
}
}
}
Output:
32416190071 is probably prime.
Output Explanation:
The program creates a BigInteger instance representing a large number and invokes isProbablePrime() with certainty 10. A return value of true indicates the number is prime with high confidence, while false confirms compositeness.
Time Complexity Analysis
When to use?
Example Scenario
Suppose you are developing a security module that generates RSA keys requiring large prime numbers. Using Java’s BigInteger isProbablePrime() method allows you to efficiently validate prime candidates with high certainty. This ensures cryptographic strength while maintaining acceptable performance, similar to how BASH or PERL scripts handle large integers in server automation.
Try implementing a segmented sieve for more efficient prime generation in large ranges. Experiment with optimizing prime-checking methods for performance in real-life applications.
You can also explore Java’s concurrency tools to speed up prime number calculations with multi-threading.
A prime number program in Java prints and checks primes using methods ranging from brute force to advanced algorithms like wheel factorization and BigInteger. To optimize, test multiple algorithms, handle edge cases, and leverage built-in Java features like BigInteger for very large numbers.
As you dive deeper, you may face challenges like handling large datasets or optimizing performance. upGrad’s courses in Java and emerging technologies can help you grow and tackle more advanced challenges.
If you want to upskill yourself in Java programming skills. These are some of the additional courses from upGrad that can help understand basic and advanced functions of Java for industry-level applications.
Curious which courses can help you gain expertise in Java and other programming languages? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center.
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
References:
https://www.netguru.com/blog/is-java-still-used-in-2025
408 articles published
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources