View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

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:

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!

How to Implement a Prime Number Program in Java to Print Prime Numbers from 1 to 100?

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. 

  • Looping through numbers: You iterate from 2 to 100, as 1 is not prime by definition. This outer loop represents the candidate numbers to check.
  • Inner divisibility check: For each candidate, a nested loop tests divisibility by all integers from 2 up to one less than the candidate. If divisible, the candidate is not prime.
  • Boolean flag usage: A boolean variable isPrime tracks whether a number passes the divisibility test. This flag is essential for controlling the flow without unnecessary checks.
  • Early loop termination: The break statement stops the inner loop as soon as a divisor is found, optimizing runtime by avoiding redundant calculations.
  • Prime number output: Numbers identified as prime via this method are printed immediately, demonstrating dynamic result generation in Java.

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

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Which Methods in Java Check and Print Prime Numbers?

 

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. 

1. How 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.

 

  • Prime check function: The isPrime(int n) method systematically tests divisibility using a for-loop, returning false if any divisor exists, and true otherwise.
  • Boundary conditions: Numbers less than or equal to 1, including zero and negatives, are excluded from primality via immediate false return, ensuring a valid input domain.
  • Divisibility testing: The loop iterates from 2 to n-1, applying the modulus operator % to determine divisibility, a critical conditional check in prime verification.
  • Immediate exit optimization: Upon detecting a divisor, the function halts further checks using a return statement, optimizing runtime by avoiding unnecessary iterations.
  • Output mechanism: The main method executes the prime check on a predefined number (17) and outputs the primality result, demonstrating program flow and boolean logic in Java.

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.

  • The brute-force prime number program in Java operates with O(n) time complexity, where n is the number being tested.
  • This linear time means the number of divisibility checks grows proportionally with the input size.
  • While inefficient for large inputs, this method remains practical for small ranges and learning 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.

  • Use this method when introducing fundamental programming concepts like loops and conditionals.
  • It is suitable for validating small numbers where performance isn’t critical.
  • Understanding brute-force primes aids transitioning to optimized algorithms in JavaScript, ReactJS, and Node.js environments.

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.

If you want to gain expertise on software development processes and industry-relevant programming skills such as Java, check out upGrad’s Generative AI Mastery Certificate for Software Development. The program will help you integrate AI and optimize your development workflows for enterprise-grade applications. 

Now’ let’s understand how you can print prime numbers in Java from 1 to 100 using the square root optimization method.

2. How to Print Prime Numbers from 1 to 100 Using the Square Root Optimization Prime Number Program in Java?

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.

  • Reduced divisor checks: Tests divisibility only up to √n, minimizing iterations and improving computational efficiency.
  • Mathematical rationale: Divisors larger than √n have complementary smaller factors already checked, eliminating redundant checks.
    Boolean flag usage: isPrime tracks primality within optimized bounds, controlling early exit on divisor detection.
  • Optimized loop termination: The inner loop breaks immediately when a divisor is found, saving processing time.
  • Cross-technology relevance: The efficiency concept translates to frontend optimizations in CSS and HTML and backend request validations in HTTP.

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.

  • Apply this method for prime checks involving moderate to large numbers where brute-force becomes inefficient.
  • It is highly recommended in interview scenarios and programming contests demanding optimized solutions.
  • The method’s principles can be extended to performance improvements in web technologies like CSS selector efficiency and HTTP request filtering.

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

3. How to Print Prime Numbers from 1 to 100 Using the 6k ± 1 Prime Number Method in Java? 

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.

  • Mathematical pattern filtering: Only numbers of the form 6k ± 1 are tested as potential primes, eliminating obvious composites.
  • Initial seed primes: The algorithm explicitly includes 2, 3, and 5, which don’t fit the pattern but are essential base primes.
  • Efficient primality check: The isPrime() function uses the square root optimization and excludes multiples of 2 and 3 early for faster execution.
  • Loop constructs: The main loop generates candidates via 6k - 1 and 6k + 1, minimizing redundant checks and improving performance.
  • Cross-language applicability: This algorithmic pattern and optimizations can be implemented similarly in C++ and C# environments, making it versatile.

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.

  • Time complexity per candidate is O(√n).
  • Candidate filtering reduces the total numbers tested, improving practical runtime.
  • The method balances speed and readability, making it efficient for mid-sized inputs.

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#.

  • Ideal for n ranging from thousands to millions, where basic optimization helps.
  • Useful in programming contests requiring efficient prime checks.
  • Applicable when algorithmic clarity is important alongside performance.

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. 

4. How to Print Prime Numbers from 1 to 100 Using the Arithmetic Prime Number Method in Java?

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.

  • Boolean marking: Uses a boolean array isPrime[] to represent primality status, similar to how tensors or arrays represent states in PyTorch or TensorFlow.
  • Early elimination: Numbers 0 and 1 are explicitly marked as non-prime to enforce domain constraints.
  • Iterative marking: Starts with the smallest prime (2) and marks all its multiples as non-prime, analogous to filtering non-significant data in tensor operations.
  • Efficient iteration: Subsequent primes are found by scanning for unmarked numbers, leveraging the property that a composite must have a prime factor less than or equal to its square root.
  • Precomputation benefits: Like MySQL indexing, the sieve’s precomputed prime list accelerates multiple queries or repeated primality checks.

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.

  • Precomputation allows instant primality queries, similar to indexed lookups in MySQL databases.
  • Space complexity is O(n), requiring memory proportional to the input size.
  • The method scales efficiently, making it suitable for large inputs and high-performance computing contexts like PyTorch or TensorFlow.

When to use?

This method generates large prime sets quickly and is favored in coding competitions and applications requiring frequent primality checks.

  • Ideal when n is large, where trial division methods become computationally expensive.
  • Useful when prime lists need to be reused across multiple operations or queries, leveraging precomputation.
  • Applicable in high-performance environments, including database indexing (MySQL) and machine learning workflows (PyTorch, TensorFlow).

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. 

5. How to Print Prime Numbers from 1 to 100 Using the Wheel Factorization Prime Number Method in Java?

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.

  • Advanced candidate filtering: Eliminates multiples of small primes early, minimizing divisibility checks.
  • Cycle-based iteration: Uses a prime wheel (e.g., 30k ± offsets) to generate only viable prime candidates.
  • Boolean sieve application: Marks composite numbers efficiently, similar to task scheduling in Kubernetes clusters.
  • Square root optimization: Primality tests are refined by limiting checks to √n.
  • Scalable design: Suitable for significant inputs and bulk prime generation, paralleling scalable container management principles.

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.

  • The method runs in O(n²) due to nested loops iterating divisors.
  • This quadratic complexity is significantly slower than optimized methods like the square root check or sieve algorithms.
  • Practical only for small input ranges or educational demonstrations.

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.

  • When learning the basics of prime detection without concern for performance.
  • For very small inputs or debugging algorithm correctness.
  • When algorithmic simplicity outweighs computational efficiency, e.g., initial Kubernetes job scripts or Docker container health checks.

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. 

6. How to Print Numbers from 1 to 100 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.

  • Divisor counting logic: For each number, counts how many integers divide it evenly, identifying primes by exactly two divisors.
  • Nested looping: Employs an outer loop over candidate numbers and an inner loop checking divisibility, reflecting straightforward control flows often seen in front-end scripting.
  • Clear condition: Primes are recognized only when the divisor count equals two, ensuring correctness without complex optimizations.
  • Readability focus: The method prioritizes code simplicity and readability, similar to clean Bootstrap markup in UI design.
  • Educational analogy: Serves as an introductory example before adopting more efficient algorithms, akin to starting with basic HTML forms before using advanced JavaScript validation in web projects.

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.

  • When working with small input ranges where performance is not critical.
  • For educational purposes to demonstrate fundamental concepts of divisibility.
  • In web development prototyping or Bootstrap-based form validation scenarios prioritizing clarity over efficiency.

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. 

How to Find a Prime Number 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.

Method 1: How to Find a Prime Number Using For Loop?

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. 

  • For each number, you check if it is divisible by any number from 2 to that number minus one. 
  • If no divisors are found, the number is considered prime.

Steps Followed

  • Loop through all numbers in the given range.
  • For each number, check divisibility from 2 to the number minus 1.
  • If the number is not divisible by any of these, it is prime.
  • Print the prime numbers.

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

  • We defined the range from 10 to 50.
  • For each number in that range, we checked divisibility starting from 2 to the number minus 1.
  • If the number is divisible by any other number, it’s marked as not prime. If it passes the divisibility test, it is considered prime.

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.

Method 2: How to Find Prime Numbers Using a While Loop?

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

  • Start with the given range.
  • Use a while loop to iterate through each number.
  • For each number, check divisibility from 2 up to the square root of the number.
  • If no divisors are found, the number is prime and is printed.

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

  • The while loop checks each number in the given range.
  • For efficiency, use an inner while loop to check divisibility up to the square root of the current number.
  • If a number has no divisors, it's identified as a prime.

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

Method 3: How to Find Prime Numbers Using Recursion?

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: 

  • If the number has been checked against all divisors up to the square root, the function returns true (if no divisors are found) or false (if a divisor is found). 
  • The recursive step involves checking divisibility and calling the function again for the next divisor.

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

  • Base Case: If the divisor exceeds the square root of the number and no divisors have been found, return true.
  • Recursive Step: Start checking divisibility from 2, and for each divisor, call the function again to check the next divisor.
  • Termination: If any divisor is found, return false. If the base case is met without finding any divisors, return true.

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?

  • Base Case: If the divisor exceeds the square root of the number, it returns true, meaning no factors were found, and the number is prime.
  • Recursive Step: The function checks if the number is divisible by the current divisor and then calls itself with the next divisor.
  • Elegance and Efficiency: It breaks the problem down into smaller checks without needing complex loops.

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.

How to Check Very Large Prime Numbers with Java’s BigInteger Method?

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

  • Miller-Rabin and related algorithms run in polynomial time relative to the number of digits, making primality testing feasible for very large integers.
  • The probabilistic nature provides rapid results with controllable error margins, balancing speed and accuracy.
  • This efficiency is essential in cryptographic applications requiring large prime generation and validation.

When to use?

  • Employ this method for cryptographic key generation and security algorithms where prime size exceeds standard numeric types.
  • Ideal for mathematical research tasks involving very large numbers that cannot be handled by primitives.
  • Useful in scripting and automation contexts using BASH or PERL where large number primality checks integrate with system operations.

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.

If you’re interested in exploring how these principles apply to cutting-edge fields like cryptography and data security, enroll in upGrad’s DBA in Emerging Technologies with Concentration in Generative AI. Master the techniques behind intelligent, data-driven applications. Start today!

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. 

How Can upGrad Help You Build a Career in Programming?

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

Frequently Asked Questions (FAQs)

1. How does the square root optimization improve prime checking performance?

2. Why is the 6k ± 1 method more efficient than brute force?

3. What advantages does wheel factorization offer over 6k ± 1 filtering?

4. When should I prefer Java’s BigInteger for primality testing?

5. How can recursion be used in prime number checking?

6. What are the trade-offs of the count divisor method?

7. How does the sieve of Eratosthenes achieve prime generation efficiency?

8. Can these prime checking methods be adapted to other languages?

9. How does early loop termination optimize prime tests?

10. Why are primes important in hashing and cryptography?

11. What considerations exist for choosing a prime checking method?

Rohan Vats

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

+91

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

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks