Java Program – Print Prime Numbers in Given Range

A prime number is a positive integer greater than 1 that has exactly two positive factors: 1 and the number itself. For example, 2, 3, 5, 7, and 11 are prime numbers. The number 6 is not prime because it is divisible by 2 and 3 in addition to 1 and 6.

In this tutorial, we write Java programs to print all prime numbers in a given range. The first example uses fixed minimum and maximum values. A second example shows how to read the range from the user using Scanner.

How to Find Prime Numbers Between Two Numbers in Java

To print prime numbers in a range, examine every integer from the lower limit to the upper limit. For each integer, test whether it has a divisor other than 1 and itself. If it has no such divisor, print it as a prime number.

You do not need to test every possible divisor up to the number itself. If a composite number num has a factor greater than its square root, the corresponding paired factor is smaller than its square root. Therefore, checking divisors only while i <= num / i is sufficient.

Example 1 – Print All Prime Numbers in a Fixed Range

In this example, the range is from 2 through 100, and both limits are included. The program calls a separate isPrime() method for every number in the range.

Algorithm to Print Prime Numbers in the Given Range

  1. Start with a minimum value min and maximum value max.
  2. Initialize n with min.
  3. Check whether n is prime by calling isPrime(n).
  4. If isPrime(n) returns true, print n.
  5. Increment n by 1.
  6. Repeat the test while n is less than or equal to max.
  7. Stop after the upper limit has been checked.

Prime Number Check Used for Each Integer

  1. Receive the number in num.
  2. Start the possible divisor i at 2.
  3. Test whether num % i == 0.
  4. If the remainder is 0, i is a divisor, so the number is not prime and the method returns false.
  5. Otherwise, continue with the next possible divisor.
  6. Only divisors up to the square-root boundary need to be tested. The condition i <= num / i performs this check without calculating a square root.
  7. If no divisor is found, return true.

Example.java

</>
Copy
/**
 * Java Program - All Prime Numbers in Given Range
 */

public class Example {

	public static void main(String[] args) {
		//range
		int min = 2;
		int max = 100;
		//find all prime numbers in the given range
		for(int n=min;n<=max;n++) {
			//check if this number is prime
			if(isPrime(n)) {
				System.out.println(n);
			}
		}
	}
	
	public static boolean isPrime(int num) {	
		for(int i = 2; i <= num/i; ++i) {
			if(num % i == 0) {
				return false;
			}
		}
		return true;
	}
}

The outer for loop visits every integer from min to max. For each value, isPrime(n) searches for a divisor. When no divisor is found, the method returns true and the number is printed.

Run the above Program, and you shall get the following output with all the prime numbers printed to the console, in the given range.

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

Why the Prime Test Stops at the Square-Root Boundary

Suppose a number can be written as a * b. If both a and b were greater than the square root of the number, their product would be greater than the number. Therefore, a composite number must have at least one factor at or below its square root.

For example, when checking 49, testing divisors through 7 is enough because 7 * 7 = 49. For 97, none of the integers from 2 through 9 divides it evenly, so 97 is prime.

The condition used in the existing program is:

</>
Copy
i <= num / i

This serves the same purpose as checking i * i <= num, while avoiding multiplication of the two loop values.

Handling 0, 1, and Negative Values in a Prime Number Range

Prime numbers are integers greater than 1. Therefore, negative integers, 0, and 1 must always be treated as non-prime.

The first example starts its range at 2, so this case does not arise there. If the range can come from user input, add an explicit check before testing possible divisors:

</>
Copy
if (num < 2) {
    return false;
}

Example 2 – Prime Numbers in a User-Entered Range Using Scanner

The following version reads the lower and upper limits from the keyboard. It also handles ranges that begin below 2 correctly.

</>
Copy
import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter lower limit: ");
        int min = scanner.nextInt();

        System.out.print("Enter upper limit: ");
        int max = scanner.nextInt();

        for (int n = min; n <= max; n++) {
            if (isPrime(n)) {
                System.out.println(n);
            }
        }

        scanner.close();
    }

    public static boolean isPrime(int num) {
        if (num < 2) {
            return false;
        }

        for (int i = 2; i <= num / i; i++) {
            if (num % i == 0) {
                return false;
            }
        }

        return true;
    }
}

For example, if the lower limit is 10 and the upper limit is 30, the program prints:

11
13
17
19
23
29

How the Java Prime Number Range Program Works

  • for (int n = min; n <= max; n++) iterates through every integer in the requested interval.
  • num < 2 excludes values that cannot be prime.
  • num % i == 0 checks whether the current divisor divides the number without a remainder.
  • Returning false immediately after finding a divisor avoids unnecessary checks.
  • If the divisor loop completes without finding a factor, the method returns true.

Inclusive Range Behavior for Prime Numbers

The loop condition uses n <= max, so the lower and upper limits are both included. If either boundary itself is prime, it is printed. For example, a range from 11 to 17 produces 11, 13, and 17.

If min is greater than max, the loop does not execute because its condition is false immediately. A program that accepts interactive input can validate this condition and ask for a correctly ordered range if required.

Time Complexity of Printing Prime Numbers in a Range

For each number, the primality test checks possible divisors only up to approximately its square root. For a range containing R numbers whose upper limit is max, a simple upper-bound description of this approach is O(R * sqrt(max)). The method uses constant extra space, apart from the input and loop variables.

Prime Numbers in a Given Range – Key Points

  • A prime number must be greater than 1.
  • Use an outer loop to visit each number between the lower and upper limits.
  • Use the remainder operator % to determine whether a possible divisor divides the number exactly.
  • Checking divisors only up to the square-root boundary is sufficient for determining primality.
  • Use <= in the range loop when both supplied limits should be included.
  • When the range may contain 0, 1, or negative numbers, explicitly return false for values below 2.

Java Prime Number Range Tutorial Summary

In this Java Tutorial, we have gone through Java program, that prints all the prime numbers in a given range of numbers.