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
- Start of Program
- Take a range[min, max]
- Initialize
n
with min. - If
n
is Prime [Call the Function – Check if Number is Prime(given below)], printn
. - Increment
n
. - If
n
is less than or equal tomax
, go to step 4. - End of Program
Function – Check if Number is Prime
- Start of Function
- Take number in
num
. - Initialize
i
with 2. - Check if
i
is a factor ofnum
. Ifi
is a factor ofnum
,num
is not prime, return False. End of the function. - If
i
is not a factor, incrementi
. This is to check if the next number is a factor. - If
i
is less thannum/i
, go to step 4. - Return true.
- 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
Conclusion
In this Java Tutorial, we have gone through Java program, that prints all the prime numbers in a given range of numbers.