Skip to main content

Prime Number Program in Java: Print All Prime Numbers

Question


  • You've to print all prime numbers between a range.
  • Take as input "low", the lower limit of the range.
  • Take as input "high", the higher limit of the range.
  • For the range print all the primes numbers between low and high (both included).

Input Format

low
high

Output Format

n1
n2
.. all primes between low and high (both included)

Constraints

2 <= low < high < 10 ^ 6

Sample Input

6
24

Sample Output

7
11
13
17
19
23

Program

import java.util.*;

public class Main{
    public static void main(String[] args) {
        // write your code here
        Scanner scn = new Scanner(System.in);
        int low = scn.nextInt();
        int high = scn.nextInt();
        for (int i = low; i <= high; i++){
            int count = 0;
            //try to divide n and incrtease count 
            for (int div = 2; div * div <= i; div++){
                if ( i % div == 0){
                    count++;
                    break;
                }
            }
            //try to divide n and incrtease count
            if (count == 0){
            System.out.println(i);
            }
        }
        
    }
}

Comments