Prime Number Program in Java - Java Program to Print Prime Numbers



Prime Number Program in Java :

  • The numbers which have only two factors, i.e. 1 and the number itself are called prime numbers. That means they are not divisible by any other numbers. Some examples of prime numbers are 7, 11, 13, 17,

Sample Code

import java.util.Scanner;

public class primenumber 
{
  public static void main(String[] args) 
  {
    int n, i, m = 0, flag = 0;
    System.out.println("Enter the Number to check Prime: ");
    Scanner sc = new Scanner(System.in);
    n = sc.nextInt();
    m = n / 2;
    for (i = 2; i <= m; i++) 
    {
      if (n % i == 0) 
      {
        System.out.println("Number is not Prime.");
        flag = 1;
        break;
      }
    }
    if (flag == 0)
      System.out.println("Number is Prime.");
  }
}

Output

Enter the Number to check Prime: 23
Number is Prime.
Enter the Number to check Prime: 39
Number is not Prime.

Related Searches to Prime Number Program in Java - Java Program to Print Prime Numbers