Java program to display prime numbers between given interval has been shown here. For example, the prime numbers between 30 and 50 are 31, 37, 41, 43, 47. In this program, the upper and lower bounds of the interval are taken as inputs.
1. Algorithm to Display Prime Numbers between Given Interval
1. Take lower bound l and upper bound u as inputs.
2. For each number from l to u, check if it is a prime number.
3. If a number is prime, add it to a list of prime numbers.
4. Display the list after all the numbers within the interval have been checked.
2. Pseudocode to Display Prime Numbers between Given Interval
Input : Lower bound $l$ and Upper bound $u$
Output : Prime numbers between $l$ and $u$
1. Procedure primesBetweenInterval($l, u$):
2.
3.
4.
5.
6.
7.
8.
9.
10. End Procedure
3. Time complexity to Display Prime Numbers between Given Interval
Time Complexity: O($n\sqrt{n}$)
Here, $n$ is the number of elements between $l$ and $u$ inclusive
4. Java Program & output to Display Prime Numbers between Given Interval
/*********************************** alphabetacoder.com Java program to display prime numbers between given intervals ************************************/ import java.util.Scanner; import java.lang.Math; class Main { // function to check prime public boolean check_prime(int num) { // declare variables int i; // no prime number less than 2, so return false if (num < 2) return false; // check divisibility for (i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; // num is composite so return false } } // num is prime so return true return true; } public static void main(String[] args) { // declare instance of Scanner class Scanner sc = new Scanner(System.in); // declare object of Main class Main obj = new Main(); // declare variables int n1, n2, i; // take input of the inteval System.out.print("Enter the lower and upper bounds of interval = "); n1 = sc.nextInt(); n2 = sc.nextInt(); System.out.print("Prime numbers between " + n1 + " and " + n2 + ": "); // find primes between n1 and n2 for (i = n1; i <= n2; i++) { // check if current number is prime // if it is prime, then print it if (obj.check_prime(i)) { System.out.print(i + " "); } } } }
Output
Enter the lower and upper bounds of interval = 100 150
Prime numbers between 100 and 150: 101 103 107 109 113 127 131 137 139 149 151