In this tutorial we will learn to write a Java program that will output all prime numbers that are in a given range.
Problem
- Our program takes two numbers as input.
- Now the program will output all prime numbers between 3 and 13.
- So the output will be 3, 5, 7, 11 and 13. Because these are the only five numbers that are prime numbers.
What is a prime number?
Prime numbers are the numbers that have only 2 factors: 1 and the number itself. It is defined only for the number that is greater than 1. 2′ is the smallest prime number.
Some examples
- 7 is a prime number because only the factors of 7 are ‘1 and 7’.
- 11 is a prime number because only the factors of 11 are ‘1 and 11’.
- 10 is not a prime number because the factors of 10 are ‘1,2,5 and 10’.
Print prime number in Java in given range
import java.util.*;
public class Main {
public static void main(String[] args) {
int i=0,fNum,sNum, temp,temp1=1;
Scanner sc = new Scanner(System.in);
System.out.println("Please give the first number");
fNum= sc.nextInt();
System.out.println("Please give the second number");
sNum= sc.nextInt();
System.out.println("Prime numbers in range "+fNum+ " and " +sNum+"are");
while(fNum<=sNum){
temp=0;
for(i=2;i<=(fNum/2);i++){
if(fNum%i==0){
temp=1;
break;
}
}
if(temp==0)
System.out.println(fNum);
fNum++;
}
}
}
Explanation
The numbers entered are 3 and 25, so our program checks all numbers less than 25 and greater than 3. The numbers that have no other factor than 1 and themselves, i.e. prime numbers in the given range are 3, 5, 7, 11, 13, 17, 19, 23
Output
Please give the first number
3
Please give the second number
25
Prime numbers in range 3 and 25are
3
5
7
11
13
17
19
23
.