Thursday, 15 October 2015

Java program to display PRIME NUMBERS between two numbers

Requirement: Write a Java program to display PRIME NUMBERS between two numbers.

Explanation: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 17 can be divided only by 17 and by 1. The only even prime number is 2. All other even numbers can be divided by 2.

Solution: The Java code of the above requirement is shown below:

Java Code:

package com.susanto;

import java.util.Scanner;

public class FindPrimeNumber {

       public static void main(String[] args) {
             Scanner scanner = new Scanner(System.in);
             int lowerLimit, upperLimit;
             System.out.println("Enter the lower limit number");
             lowerLimit = scanner.nextInt();
             System.out.println("Enter the upper limit number");
             upperLimit = scanner.nextInt();
             System.out.println("Prime no. between " + lowerLimit + " and " + upperLimit + " are: ");
             for (int i = lowerLimit; i <= upperLimit; i++) {
                    int j;
                    for (j = 2; j < i; j++) {
                           int n = i % j;
                           if (n == 0) {
                                 break;
                           }
                    }
                    if (i == j) {
                           System.out.print(i+" ");
                    }
             }
       }
}


Output:

Enter the lower limit number
1
Enter the upper limit number
15
Prime numbers between 1 and 15 are:
2 3 5 7 11 13


Hence, the solution to our requirement.

If you really like the post and want to get updated of my upcoming posts, then join susantopaul.com on: Facebook and LinkedIn.

Please don’t forget to share and comment on the post.

Thanks & Regards,
Susanto Paul