Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

How to Write a Prime Number Program in Java: Display 1 to 100 in Java

Updated on 17 December, 2024

45.65K+ views
19 min read

Prime numbers are more than just a math concept—they’re essential in programming. Take encryption, for example. Have you wondered how it works? It relies on the difficulty of breaking down large prime numbers into factors. Their unique property of being divisible only by 1 and themselves makes them crucial for creating secure systems.

If you're looking to advance your career in tech, understanding how to work with prime numbers, especially in Java, is a must. This blog will walk you through how prime numbers are used in everything from cryptography to algorithm design, giving you hands-on techniques to solve complex problems. 

Mastering this skill will boost your coding expertise and open doors to high-demand roles in cybersecurity, data science, and software development. 

Ready to level up? Dive in and start mastering prime numbers in Java today!

What is a Prime Number?

A prime number is a number that is greater than 1 and cannot be divided evenly by any number except for 1 and itself. In other words, a prime number has only two factors: 1 and the number itself. This unique property makes primes stand out in the world of mathematics and programming.

Real-World Applications: Prime numbers are crucial in technology and security. For instance, they are the backbone of public-key cryptography, such as RSA. Prime numbers are also essential in hash functions for data integrity and random number generation for simulations and secure algorithms.

Also Read: How to Generate Random Number in Python [Code with Use Case Examples]

What is the Logic to Check for a Prime Number?

To check if a number is prime when you are trying to print prime numbers from 1 to 100 in java, the basic logic is to see if it can be divided by any number other than 1 and itself. If it can, it’s not prime. If it can’t, then it is a prime number. This method is efficient and critical in applications involving large primes.

Also Read: Python Program To Check Prime Number

How to Print Prime Numbers From 1 to 100 in Java?

Learning to print prime numbers from 1 to 100 in Java is a great way to dive deeper into loops, conditional probabilities, and basic algorithmic thinking. By the end of this, you’ll be able to generate all the prime numbers between 1 and 100, and you’ll have a solid grasp on how prime number checking works in programming.

Let’s break this down into simple steps and the corresponding algorithm.

Algorithm and Steps:

  1. Initialize a loop to go through each number from 2 to 100.
  2. For each number in the loop, check divisibility:
  • If the number is divisible by any number from 2 to itself minus 1, it’s not prime.
  • If no divisors are found, it is a prime number.
  1. Print the prime numbers as you go.

Steps for the Program:

  1. Start with a for loop that goes from 2 to 100. The loop will check each number to determine if it’s prime.
  2. For each number, run another loop that goes from 2 to that number minus 1. If the current number is divisible by any of these, you can stop the check and move on to the next number.
  3. If no divisors are found, the number is prime, so print it.

Sample Java Code:

public class PrimeNumber {
    public static void main(String[] args) {
        // Loop through numbers from 2 to 100
        for (int num = 2; num <= 100; num++) {
            boolean isPrime = true;  // Assume the number is prime
            
            // Check divisibility from 2 to num-1
            for (int i = 2; i < num; i++) {
                if (num % i == 0) {  // If divisible, it's not prime
                    isPrime = false;
                    break;
                }
            }
            
            // If the number is still prime, print it
            if (isPrime) {
                System.out.println(num);
            }
        }
}
}

Also Read: Length Of String In Java

Explanation:

  • The outer loop runs through every number from 2 to 100.
  • The inner loop checks if the number is divisible by any number between 2 and the number minus 1.
  • If it finds any divisor, the number is not prime, and the program moves to the next number.
  • If no divisors are found, the number is prime and gets printed.

Why This Works:

This program uses brute-force to check primality: For each number, we test whether it can be divided by any number smaller than itself. While this approach is easy and understandable, it’s not the most efficient for large numbers. 

In real-world applications, especially cryptography, more optimized algorithms are used. However, this method works perfectly for smaller ranges like 1 to 100 and is a great way to practice working with loops and conditionals.

Example 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

By following this simple algorithm, you’ll be able to list out all prime numbers between 1 and 100 in just a few lines of Java code!

Also Read: Coding vs Programming: Difference Between Coding and Programming

What are the Different Methods to Print Prime Numbers in Java?

Prime numbers are fundamental to computer science, cryptography, and various algorithms. But when it comes to programming, you’ll find that there are several ways to identify prime numbers in Java. 

In this section, you’ll explore different methods to print prime numbers from 1 to 100 in Java. These methods vary in complexity and efficiency, so let’s take a look at each one!

Method 1: Print Prime Numbers from 1 to 100 in Java using Simple Method

The simple method of finding prime numbers involves checking each number individually to see if it can be divided by any number smaller than itself. If a number has no divisors other than 1 and itself, it is a prime number.

Explanation:

In this method, you iterate through all numbers from 2 to 100 and for each number, check if it’s divisible by any number between 2 and one less than the number itself. If no divisors are found, then it’s prime!

Working Algorithm Steps:

  • Loop through numbers from 2 to 100.
  • For each number, check if it is divisible by any number between 2 and the number minus 1.
  • If no divisors are found, print the number as prime.

Example Code:

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);
            }
        }}
}

Benefits and Drawbacks:

  • Benefits: This method is simple to understand and easy to implement.
  • Drawbacks: It's inefficient for larger numbers because it checks divisibility up to the number itself. As the number increases, this method becomes slower, especially when working with large primes in cryptography or data processing.

Also Read: Packages in Java & How to Use Them?

Method 2: Print Prime Numbers from 1 to 100 in Java using Square Root Method

The square root method optimizes the simple method by limiting the number of divisibility checks. Instead of checking divisibility up to the number itself, you only need to check up to the square root of the number. This significantly reduces the number of checks, especially for larger numbers.

Explanation:

A number doesn’t need to be divisible by any number greater than its square root. If a number is divisible by a factor larger than its square root, the corresponding smaller factor would have already been detected. This method dramatically improves efficiency for larger numbers.

Working Algorithm Steps:

  • Loop through numbers from 2 to 100.
  • For each number, check divisibility from 2 to the square root of that number (rounded up).
  • If no divisors are found, the number is prime.

Example Code:

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);
            }
        }
    }
}

Benefits and Drawbacks:

  • Benefits: More efficient than the simple method, as it reduces the number of divisibility checks by checking only up to the square root of each number.
  • Drawbacks: This method still becomes inefficient for very large numbers, although it's much better for moderately sized numbers.

Also Read: Perfect Number Program for Java

Method 3: Print Prime Numbers from 1 to 100 in Java Using Arithmetic Method

The arithmetic method for finding prime numbers is an efficient way to filter out primes using mathematical patterns. One such approach leverages the observation that all prime numbers greater than 3 can be expressed in the form:

  • 6k+1
  • 6k-1

where k is a positive integer. This method allows us to reduce the range of numbers to check, making it faster than checking each number individually.

Algorithm:

  • Start with an initial list containing 2 and 3, the only even prime and the first odd prime.
  • Use a loop to generate potential prime numbers using the arithmetic formulas 6k1.
  • For each generated number, check if it is divisible by any number up to its square root.
  • Mark multiples of these numbers as non-prime.

Code Implementation:

import java.util.ArrayList;

public class PrimeNumberArithmeticMethod {
    public static void main(String[] args) {
        int n = 100; // Upper limit to find primes up to 100
        ArrayList<Integer> primes = new ArrayList<>();

        // Step 1: Add 2 and 3 explicitly, as they are the only even prime and first odd prime
        primes.add(2);
        primes.add(3);

        // Step 2: Generate numbers using the 6k ± 1 pattern and check for primality
        for (int i = 1; i <= n / 6; i++) {
            int num1 = 6 * i - 1; // 6k - 1
            int num2 = 6 * i + 1; // 6k + 1

            // Check if num1 is prime and within the limit
if (num1 <= n && isPrime(num1)) {
                primes.add(num1);
            }

            // Check if num2 is prime and within the limit
            if (num2 <= n && isPrime(num2)) {
                primes.add(num2);
            }
        }

        // Step 3: Print the prime numbers
        System.out.println("Prime numbers from 1 to " + n + ": " + primes);
    }

    // Helper method to check if a number is prime
    public static boolean isPrime(int num) {
        if (num <= 1) return false; // 0 and 1 are not prime
        if (num <= 3) return true; // 2 and 3 are prime numbers

        // Eliminate even numbers and multiples of 3
        if (num % 2 == 0 || num % 3 == 0) return false;

        // Check divisibility up to the square root of num
        for (int i = 5; i * i <= num; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) return false;
        }

        return true;
    }
}

Explanation of the Code: The list primes is initialized with the first two prime numbers, 2 and 3. The loop generates numbers using the 6k1 pattern and checks if they are prime using the isPrime() helper method. 

The method isPrime() checks if a number is prime by first ruling out even numbers and multiples of 3. It then checks divisibility only up to the square root of the number to ensure efficient computation. The program prints the generated prime numbers up to 100.

Benefits and Drawbacks:

  • Benefits: This method is highly efficient for larger numbers. It skips numbers that don’t fit the 6k1 form, reducing unnecessary checks.
  • Drawbacks: The logic is slightly more complex than the simple methods, but it provides a significant performance boost.

Also Read: Abstract Class in Java and Methods [With Examples]

Method 4: Print Prime Numbers from 1 to 100 in Java Using Count Method

The count method involves counting the number of divisors for each number. If the count is exactly two (1 and the number itself), it is a prime number. This method offers a straightforward way to check for primes, although it’s not as efficient as the square root or 6k1 methods.

Explanation:

In this method, you count how many numbers divide into the current number. If only two divisors are found (1 and the number itself), the number is prime.

Working Algorithm Steps:

  • Loop through numbers from 2 to 100.
  • For each number, count how many times it can be divided evenly by another number.
  • If the count is exactly 2, the number is prime.

Example Code:

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);
            }
        }
    }
}

Benefits and Drawbacks:

  • Benefits: Simple to implement and understand.
  • Drawbacks: This method is inefficient because it requires counting divisors for each number, which can become slow for larger numbers.

Each of these methods has its strengths and weaknesses. The simple method is suitable for beginners but inefficient for large numbers. The square root method is an improvement in efficiency, while the 6k1 technique offers the best performance for larger numbers. 

The count method, though simple, is slow and should be avoided for more extensive ranges. Choosing the right approach depends on the problem at hand and the performance requirements for your program!

Also Read: Method Overloading in Java [With Examples]

 

Ready to begin your Java development journey? Explore upGrad’s free courses to get a solid foundation in programming and start learning today. Start Learning Now!

 

How to Find a Prime Number in Java?

Finding prime numbers in a given range is an essential task in many programming problems, especially in fields like cryptography, number theory, and data science. A prime number is a number greater than 1 that cannot be divided by any number other than 1 and itself. 

But how do you find prime numbers within a range, say between two given numbers, in Java?

It involves iterating through the numbers in a given range and checking each one to see if it meets the criteria of being a prime. This process generally requires checking divisibility from 2 up to the number minus one.

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

Overview of the Method:

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:

  1. Loop through all numbers in the given range.
  2. For each number, check divisibility from 2 to the number minus 1.
  3. If the number is not divisible by any of these, it is prime.
  4. 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);
            }
        }
    }
}

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.

Benefits:

  • Easy to understand and implement.
  • Works well for small ranges.

Drawbacks:

  • It is inefficient for large numbers or ranges because it checks divisibility up to n−1, which becomes slow as the numbers grow larger.

Also Read: For-Each Loop in Java [With Coding Examples]

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 when you don’t know the number of iterations in advance.

Overview of the Method:

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:

  1. Start with the given range.
  2. Use a while loop to iterate through each number.
  3. For each number, check divisibility from 2 up to the square root of the number.
  4. 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++;
        }
    }
}

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.

Benefits:

  • Similar to the for loop but offers more flexibility with iteration.
  • More control over the conditions inside the loop.

Drawbacks:

  • It can still be inefficient for larger ranges since we check divisibility for each number.

Also Read: Python While Loop Statements: Explained With Examples

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.

Overview of the Method:

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:

  1. Base Case: If the divisor exceeds the square root of the number and no divisors have been found, return true.
  2. Recursive Step: Start checking divisibility from 2, and for each divisor, call the function again to check the next divisor.
  3. 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 It Works:

  • 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

Recursion's elegance lies in its simplicity: It breaks the problem down into smaller checks without needing complex loops. However, while recursive functions are clean and easy to read, they can be inefficient for larger numbers due to the overhead of multiple function calls. 

For example, in large ranges, each additional recursive call adds memory and processing time, which can significantly slow down the program. In such cases, iterative methods or optimized algorithms like the Sieve of Eratosthenes might be a better choice.

Key Takeaways:

  • Elegance: Recursion offers a straightforward and intuitive way to check for prime numbers, especially for smaller ranges.
  • Inefficiency: For larger numbers or ranges, recursion can become inefficient due to function call overhead.
  • Best Use Case: Ideal for learning and small-scale problems, but less effective when performance is a concern in large-scale applications.

Recursion’s beauty lies in its simplicity, but when working with larger datasets, you’ll need to balance elegance with efficiency. Keep experimenting with different methods, and soon you’ll be mastering both the theory and practice of prime number algorithms!

Also Read: Recursion in Data Structure: How Does it Work, Types & When Used

In Java, there are several ways to find prime numbers in a range, each with its pros and cons. For smaller ranges, a for or while loop works well, while larger numbers may require optimized methods like the square root approach or recursion. Choose the method based on the size and complexity of your problem.

As you develop these skills, you might wonder how you can turn them into a successful career. upGrad can help!

How Can upGrad Help You Build a Career in Programming?

Building a career in programming is no longer just about writing lines of code—it’s about mastering the real-world skills that companies demand. upGrad ensures that you learn and apply what you learn to solve real challenges. 

Here’s how upGrad helps you build the expertise needed to succeed in the world of coding:

  • Hands-On Learning: Build real-world projects like face detection systems for practical, applied experience.
  • Personalized Mentorship: Get one-on-one guidance to master complex topics and receive career advice.
  • Industry-Relevant Skills: Focus on in-demand technologies and tools, like Python and OpenCV, to stay ahead.

Here are a few upGrad coding and programming courses that will help you launch your development career: 

Course Title

Description

Java Object-oriented Programming Master the fundamentals of Object-Oriented Programming (OOP) in Java with this free course, and learn key concepts like classes, inheritance, and polymorphism.
JavaScript Basics from Scratch This free course offers a comprehensive introduction to fundamental programming concepts and web development skills using JavaScript.
Master of Design in User Experience Earn a Master’s in User Experience Design from Jindal School of Art and Architecture, and gain expertise in creating intuitive, user-centered designs for digital products.
Best Full Stack Developer Bootcamp 2024 A program designed to equip learners with essential skills in both front-end and back-end development, preparing them for successful careers in software engineering.
Python Programming Free Courses | Basic Python Free Course This free course offers 12 hours of learning to develop problem-solving skills through coding exercises on lists, strings, and data structures like tuples, sets, and dictionaries.

 

Ready to kickstart your development career? Book a free career counseling session with upGrad today and start building the future you’ve always dreamed of.

 

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.

Frequently Asked Questions (FAQs)

1. Why are prime numbers important in cryptography?

Prime numbers are used to create encryption keys in cryptography. Their complexity and difficulty to factorize into smaller numbers make them ideal for securing data transmissions.

2. Can you generate prime numbers using recursion in Java?

Yes, recursion can be used to generate prime numbers, though it's less efficient than iterative methods due to higher function call overhead.

3. What is the Sieve of Eratosthenes algorithm, and how is it used to find prime numbers?

The Sieve of Eratosthenes is an ancient algorithm that efficiently finds all primes up to a specified limit by iteratively marking the multiples of each prime number.

4. How can prime numbers be used in hashing algorithms?

Prime numbers are often used in hashing algorithms to reduce the likelihood of hash collisions, improving the performance of data storage and retrieval.

5. What is the role of prime numbers in random number generation?

 Prime numbers are used in algorithms to generate pseudo-random numbers, which are critical for simulations, cryptography, and gaming.

6. Can prime numbers help improve the efficiency of sorting algorithms?

While prime numbers don't directly impact sorting algorithms, they can be used in optimization techniques like dividing data into smaller chunks for more efficient processing.

7. What challenges arise when working with large prime numbers in Java?

Large prime numbers can be computationally expensive to test and store, leading to performance issues in algorithms that require them for encryption or other mathematical operations.

8. What is the "6k ± 1" rule in prime number generation?

This rule helps optimize the search for primes by checking only numbers of the form 6k ± 1, as primes (other than 2 and 3) are always close to multiples of 6.

9. How do you handle prime number generation for very large ranges in Java?

 For large ranges, more advanced algorithms like the segmented sieve or optimized trial division methods can be used to efficiently generate prime numbers.

10. What are some limitations when working with prime numbers in machine learning models?

Prime numbers are rarely directly used in machine learning, but their properties can sometimes aid in feature selection and certain algorithm optimizations.

11. Are there any real-world applications of prime numbers outside of programming?

Yes, prime numbers appear in areas like music theory (for rhythm patterns), art (for geometric designs), and biology (in patterns like the arrangement of seeds in a sunflower).

RELATED PROGRAMS