Java Program for Prime Numbers Within a Range

In this article, we will write a Java program to identify all the prime numbers within a given range.

The Strategy

To list the prime numbers within a range: 

  • We'll iterate through every number in the specified range. 
  • For each number, we'll check if it's prime. 
  • If it's prime, we'll print it. 

Java Program

public class PrimeRangeFinder {

    public static void main(String[] args) {
        int start = 1;
        int end = 100;

        System.out.println("Prime numbers between " + start + " and " + end + " are:");
        for (int i = start; i <= end; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }
    }

    public static boolean isPrime(int num) {
        if (num < 2) return false;
        if (num == 2) return true;
        if (num % 2 == 0) return false;
        
        int sqrt = (int) Math.sqrt(num);
        for (int i = 3; i <= sqrt; i += 2) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Output:

We will find all the prime numbers between 1 to 100:
Prime numbers between 1 and 100 are:
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
You can specify the range by changing start and end variable values in the program.

Step by Step Explanation: 

Setting the Range:

        int start = 1;
        int end = 100;

Here, we've set the range between 1 and 100. You can modify these values to choose a different range.

 Looping Through the Range:

        for (int i = start; i <= end; i++) {

We iterate through every number within our range using a for loop.

 Checking if a Number is Prime:

            if (isPrime(i)) {

We use the isPrime method (which we'll discuss next) to determine if a number is prime. If it's prime, we print it. 

The isPrime Method: 

Numbers Less Than 2: Numbers less than 2 aren't prime.

        if (num < 2) return false;

Number is 2: 2 is the only even prime number.

        if (num == 2) return true;

Even Numbers (except 2): All other even numbers are not prime.

        if (num % 2 == 0) return false;

Check Odd Divisors: We only check odd numbers because, beyond 2, no even number can be a factor of a prime. We check up to the square root (sqrt) of the number for reasons discussed previously.

        int sqrt = (int) Math.sqrt(num);
        for (int i = 3; i <= sqrt; i += 2) {

Conclusion

Identifying prime numbers is a classic problem in the world of programming. With this beginner-friendly guide, you have learned to craft a program that does exactly that for a given range. As you continue your Java journey, consider exploring more complex algorithms and dive deeper into the world of number theory. Remember, every complex problem starts with understanding the basics. Happy coding!

Comments