Java program to Print Prime Number in Given Range

print prime number given range java

In this tutorial, we will learn writing Java program to print all the prime numbers that are present in the given range.

Problem Statement

  • Our program will take two numbers as an input. For example user has given 3 and 13 as an input.
  • Now program will print all the prime numbers between 3 and 13.
  • So output will be 3, 5, 7, 11 and 13. Because this is the only five numbers which is prime.

What is Prime Number?

Prime Numbers are the numbers that have only 2 factors 1 and the number itself. It is only defined for the number which is greater than ‘1’. ‘2’ is the smallest prime number.

Some examples

  • 7 is a prime number because only factors of 7 are ‘1 and 7’.
  • 11 is a prime number because only factors of 11 are ‘1 and 11’.
  • 10 is not prime because the factors of 10 are ‘ 1,2,5 and 10’.

Print Prime Number In Java In Given Range

Output

Explanation

The input numbers are 5and 20, so our program will check all the numbers smaller than 20 and greater than 5. The numbers that do not have any other factor other than 1 and itself, i.e. prime numbers in the given range are 5, 7, 11,13,17,19.