Pages

Friday, November 13, 2020

Java Program to Print Prime Numbers Between Two Intervals

1. Overview

In this tutorial, you'll learn how to display the prime number in between two numbers or intervals.

These intervals can be assumed as low and high values for the prime numbers range.

In other words, we need to print only the prime values for those two numbers range.

Let us take one sample example.

Range: low = 20, high = 30
Output: 23, 29

This problem can be solved using the following java basics.



2. Java Example To Print Prime Numbers for Two Intervals


public class PrintPrimeTwoInterval {

	public static void main(String[] args) {

		// declaring two integer variables for low and high
		int low = 20;
		int high = 30;

		// run the loop from low to till high
		while (low <= high) {

			// this holds the prime status of current number
			boolean isPrime = true;

			for (int i = 2; i <= low / 2; i++) {

				if (low % i == 0) {
					isPrime = false;
					break;
				}
			}

			if (isPrime && low > 1) {
				System.out.print(low + " ");
			}

			// increasing the low by 1 and this is considered as next number
			low++;
		}
	}

}

Output:
23 29 
In the above program, first created two variables to store the start and end index as in low and high variables.

Next, loop through from low to high value using while loop.

Initialize a boolean isPrime variable with value true and it is set to false inside for loop if condition.

Inside while loop check the every number in between low and high is prime or not. If the number is prime then print the value and go for next number.

Once the low value becomes greater than high value then it comes out of while loop.

Finally, this program terminates from execution.

3. Conclusion


In this quick article you have seen how to get all the prime numbers for a given range.


No comments:

Post a Comment

Please do not add any spam links in the comments section.