1. Home

Step by Step Java Tutorial Concepts - From Beginner to Pro

Learn Java programming from basics to advanced concepts with our comprehensive tutorials. Start from scratch and elevate your skills to expert level.

• 192 Lessons
• 32 Hours
181

# Java Program to Print Prime Numbers in a Given Range

Updated on 19/07/20244,163 Views

## Overview

Java programming presents one of the most interesting numerical challenges, especially for beginners: writing a Java program to print prime numbers in a given range.

This tutorial covers the essentials for creating a Java program that effortlessly identifies and displays prime numbers within the user-specified range. Learn about efficient algorithms and unleash the power of Java as we explore this intriguing topic.

## Prime Numbers Between a Given Range in Java - Introduction

So, what is a prime number? It is a positive integer value greater than 1 and leaves no remainder unless divided by 1 and itself. Prime numbers are crucial in various mathematical and computational applications, such as generating random numbers, primality testing, optimizing algorithms like prime factorization and discrete logarithm problems, and cryptography.

This tutorial will focus on finding prime numbers within a defined range. This range will be specified by the user, and the aim of the program will be to detect and print all prime numbers that lie in this user-specified range.

When you have to print prime numbers from 1 to n in Java, there are several methods you can employ other than the Brute Force Method, which involves checking the divisibility of each number within the specified range by all numbers up to its square root. This tutorial discusses the Sieve of Eratosthenes, the Trial Division, the Miller-Rabin Primality Test, and the Lucas-Lehmer Test (for Mersenne Primes).

## Methods to Find All the Prime Numbers in a Given Interval in Java

Multiple methods exist to find all the prime numbers in a given range or interval in Java. Let us learn more about some of the more important methods.

### Naive Approach

`public class upGrad {    public static void main(String[] args) {        int start = 1; // Starting number of the interval        int end = 100; // Ending number of the interval        System.out.println("Prime numbers between " + start + " and " + end + " are: ");        for (int i = start; i <= end; i++) {            if (isPrime(i)) {                System.out.print(i + " ");            }        }    }    // Method to check if a number is prime    public static boolean isPrime(int number) {        if (number <= 1) {            return false;        }        // Check from 2 to square root of the number        for (int i = 2; i <= Math.sqrt(number); i++) {            if (number % i == 0) {                return false;            }        }        return true;    }}`

The main method defines the starting and ending numbers of the interval. It prints the message indicating the range of numbers being considered.

Next, it iterates through each number within the interval using a for loop. It calls the isPrime method for each number to check if it is prime. The isPrime method takes a number as input and returns true if the number is prime and false otherwise.Within the isPrime method, it first checks if the number is less than or equal to 1. If so, it returns false since 1 and numbers less than 1 are not prime.

Next, it iterates from 2 to the square root of the number. If any divisor is found between 2 and the square root, the number is not prime and returns false. If no divisor is found, the number is prime, and the isPrime method returns true.

Each prime number within the given range or interval is printed on the console.

### Sieve of Eratosthenes Method

`import java.util.Arrays;public class upGrad {    public static void main(String[] args) {        int limit = 100; // Limit to find prime numbers        System.out.println("Prime numbers up to " + limit + " are: ");        boolean[] primes = findPrimes(limit);        for (int i = 0; i <= limit; i++) {            if (primes[i]) {                System.out.print(i + " ");            }        }    }    // Function to find all prime numbers up to a given limit    public static boolean[] findPrimes(int limit) {        boolean[] primes = new boolean[limit + 1];        Arrays.fill(primes, true);        primes[0] = primes[1] = false;        for (int i = 2; i * i <= limit; i++) {            if (primes[i]) {                for (int j = i * i; j <= limit; j += i) {                    primes[j] = false;                }            }        }        return primes;    }}`

The main method sets the limit up to which prime numbers need to be found and prints the message indicating the limit being considered. It calls the findPrimes method, passing the limit as a parameter, which returns a boolean array indicating whether each number up to the limit is prime.

Within the findPrimes method, it initializes a boolean array called primes with a size of limit + 1. All values are initially set to true, assuming every number is prime. It explicitly sets primes[0] and primes[1] to false since they are not prime numbers. It iterates from 2 to the square root of the limit using a for loop.

For each i value within the loop, it checks if primes[i] is true. If primes[i] is true, i is a prime number. Hence, it iterates from i * i up to the limit, incrementing by i each time. This inner loop sets the value of primes[j] to false, marking j as a non-prime number since it is divisible by I.

Once all multiples of i are marked as non-prime, the outer loop continues to the next i value. Finally, the findPrimes method returns the primes array. The main method iterates through the primes array and prints the indices (prime numbers) for which the corresponding value is true.

### Optimized Approach using Trial Division

This example calls the findPrimes method, passing the start and end values as parameters, which returns a list of prime numbers within that interval. The isPrime method checks if the number is less than or equal to 1. If so, it immediately returns false since 1 and numbers less than 1 are not prime.

It then iterates from 2 to the square root of the number. If any divisor is found, the number is not prime and returns false. If no divisor is found, the number is prime, and the isPrime method returns true. Back in the findPrimes method, if a number is determined to be prime, it is added to the primes list.

### Sieve of Eratosthenes with Segmented Approach

The program utilizes the segmented Sieve of Eratosthenes algorithm to efficiently find prime numbers within a given interval by dividing the interval into smaller segments and performing the Sieve of Eratosthenes on each segment individually, generating prime numbers within that segment and then combining them into the final result. This approach allows for efficient prime number generation even

It calculates the segmentSize as the square root of the end value plus 1. This value determines the size of each segment for the segmented Sieve of Eratosthenes algorithm.

It creates a boolean array called primes with a size equal to segmentSize. This array will mark numbers as prime or not within the first segment.

It creates an empty list called result to store the prime numbers within the given interval.

It performs the Sieve of Eratosthenes algorithm on the first segment, marking the numbers as prime or not in the primes array. It iterates from 2 to the square root of segmentSize and checks if each number is marked as prime in the primes array.

If a number is marked as prime, it iterates from its square value and increments by the number itself, marking the multiples as non-prime in the primes array. After completing the Sieve of Eratosthenes for the first segment, the algorithm generates primes in each segment. It iterates from start to end, incrementing by the segmentSize. It calculates the segmentEnd as the current segment's end value, ensuring it does not exceed the overall end value.

## Java Program to Print Prime Numbers in a Given Range Using for Loop

`import java.util.ArrayList;import java.util.List;public class upGrad {    public static void main(String[] args) {        int start = 1; // Starting number of the interval        int end = 100; // Ending number of the interval        System.out.println("Prime numbers between " + start + " and " + end + " are: ");        List<Integer> primes = findPrimes(start, end);        for (int prime : primes) {            System.out.print(prime + " ");        }    }    // Method to find all prime numbers within a given interval using a simple for loop    public static List<Integer> findPrimes(int start, int end) {        List<Integer> primes = new ArrayList<>();        for (int number = start; number <= end; number++) {            if (isPrime(number)) {                primes.add(number);            }        }        return primes;    }    // Method to check if a number is prime    public static boolean isPrime(int number) {        if (number <= 1) {            return false;        }        for (int i = 2; i <= Math.sqrt(number); i++) {            if (number % i == 0) {                return false;            }        }        return true;    }}`

The main method sets the starting number (start) and ending number (end) of the interval.

It prints a message indicating the range of numbers being considered. It calls the findPrimes method, passing the start and end values as parameters, which returns a list of prime numbers within that interval.

The findPrimes method takes the start and end values and returns a list of prime numbers within that interval. It initializes an empty list called primes to store the prime numbers. It uses a for loop to iterate from start to end (inclusive) and checks each number individually.

It calls the isPrime method for each number to check if it is prime. The isPrime method checks if the number is less than or equal to 1. If so, it immediately returns false since 1 and numbers less than 1 are not prime. It then iterates from 2 to the square root of the number. If any divisor is found, the number is not prime and returns false.

If no divisor is found, the number is prime, and the isPrime method returns true.

Back in the findPrimes method, if a number is determined to be prime, it is added to the primes list. Finally, the findPrimes method returns the list of prime numbers within the given interval. The main method iterates through the primes list and prints each prime number on the console.

## Conclusion

In this tutorial, we have delved into the programming details of prime numbers in Java. By learning to identify and print prime numbers from 1 to n in Java, you can gain a valuable skill set for various mathematical and computational applications. Remember, prime numbers are not just abstract concepts; they are significant in cryptography, optimization algorithms, and other computational fields.

After mastering these techniques of determining prime numbers in Java, you might wish to explore your interest in other programming languages such as C, C++, Python, and so on. If you wish to learn more about topics such as finding out the prime number between a given range in C, or computational functions with other programming interfaces, you can always check out the array of interesting courses upGrad offers.

## FAQs

1. Can I use for loop to write a Java program to print prime numbers in a given range?

To write a Java program that gives you the prime numbers in a given range, you can run a for loop that individually determines all the prime numbers.

2. How do I optimize the prime number program for larger ranges?

You can use the Sieve of Eratosthenes algorithm to optimize the program for larger ranges. This algorithm helps identify all prime numbers up to a given limit. The algorithm significantly reduces the number of iterations required by eliminating multiples of each prime number found.

3. Can I use Java libraries or methods for prime number generation?

Yes, Java provides libraries and methods that can help generate prime numbers. The `java.util` package includes the `BigInteger` class, which provides methods like `isProbablePrime()` for primality testing. Additionally, the Apache Commons Math library offers functions for prime number generation.

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More

###### Need More Help? Talk to an Expert
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. We’re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...