Java Program to Find Prime Numbers in a Range

A number is called a prime number if it has only two divisors, 1 and the number itself. So the only way to express the number as a product of two numbers is,  n = n * 1.  For example, 7 is a prime number while 8 is not since 8 = 2 * 4.

There are various algorithms to find whether a number is a prime number or not. One of the easiest and slowest methods is  the trial division method. In this method we divide the number to be checked with numbers ranging from 2 to square root of the number and see whether any of them is a divisor (a number which can divide without leaving a remainder) of the number. The reason why we need to check only up to square root is because if  n = a * b, both a and b cannot be greater than square root of n!

Finding Prime Numbers in a Range of Natural Numbers

The following Java program finds all the prime numbers in a given range of natural numbers. This program uses the trial division technique for checking whether a number is prime or not. The program also prints out the total number of prime numbers found in the range.

/* Java program to find prime numbers in a range of natural numbers */

public class PrimeNumberRange {

    public static void main(String[] args) {
        long starting_number = 2L;
        long ending_number = 100L;
        long totals = 0;

        System.out.println("List of prime numbers between " + starting_number + " and " + ending_number);

        for (long current = starting_number; current <= ending_number; current++) {
            long sqr_root = (long) Math.sqrt(current);
            boolean is_prime = true;
            for (long i = 2; i <= sqr_root; i++) {
                if (current % i == 0) {
                    is_prime = false; // Current is not prime.
                }
            }
            if (is_prime) {
                System.out.println(current);
                totals++;
            }
        }
        System.out.println("There are a total of "+totals+" prime numbers between "+starting_number+" and "+ending_number);
    }
}

Note that for ranges containing large numbers, this algorithm is very slow due to the sheer number of mathematical operations required.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply