Java Program – Print Prime Numbers in Given Range

A number is said to be Prime Number, if it has only 1 and itself as factors. In this program, we shall try to find the factors of a number, and if it has atleast one factor other than 1 and itself, we shall decide that it is not a prime number.

In this tutorial, we shall write a Java Program that prints all prime numbers in a given range.

Example 1 – Print All Prime Number in Given Range

In this example, we shall use the following algorithm to print all the prime numbers with in the given range, including the limits.

Algorithm

  1. Start of Program
  2. Take a range[min, max]
  3. Initialize n with min.
  4. If n is Prime [Call the Function – Check if Number is Prime(given below)], print n.
  5. Increment n.
  6. If n is less than or equal to max, go to step 4.
  7. End of Program

Function – Check if Number is Prime

  1. Start of Function
  2. Take number in num.
  3. Initialize i with 2.
  4. Check if i is a factor of num. If i is a factor of num, num is not prime, return False. End of the function.
  5. If i is not a factor, increment i. This is to check if the next number is a factor.
  6. If i is less than num/i, go to step 4.
  7. Return true.
  8. End of Function

Example.java

/**
 * 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;
	}
}

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
ADVERTISEMENT

Conclusion

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