Number is prime or not in Java


The Java program takes a user input number and checks whether it is a prime number or not.

  • The program starts by importing the Scanner class from the java.util package, which is used to take user input from the console.
  • Then, the program creates a Scanner object in to read input from the console. The user is prompted to enter the number to be checked for primality.
  • Inside the for loop, the program checks whether each number from 1 to n is a factor of n. If n is exactly divisible by a number, then the f variable is incremented. At the end of the loop, f will contain the total number of factors of n.
  • If the value of f is exactly 2, then n has only two factors (1 and n), and therefore, it is a prime number. Otherwise, n has more than two factors, and it is not a prime number.

Source Code

import java.util.Scanner;
 
public class prime {
    //Write a program to check the given number is prime or not.
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter The Number : ");
        int n = in.nextInt();
        int f = 0;
        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                f++;
            }
        }
        if (f == 2) {
            System.out.println(n + " is a Prime Number");
        } else {
            System.out.println(n + " is not a Prime Number");
        }
 
    }
}
 
 

Output

Enter The Number : 17
17 is a Prime Number
Enter The Number : 10
10 is not a Prime Number
To download raw file Click Here

Basic Programs