Simple Java Program to Check if a Number is Prime


Java Tutorial

Simple Java Program to Check if a Number is Prime

import Scanner class from util package.


import java.util.Scanner;

Source code:


import java.util.Scanner;

class CheckPrimeNum {
    static boolean checkPrime(int num) {
        boolean isPrime = true;

        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = false;
            }
        }
        return isPrime;
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the Number");
        int num = sc.nextInt();
        checkPrime(num);

        if (checkPrime(num)) {
            if (num == 1) {
                System.out.println("Neither prime nor composite");
            } else {
                System.out.println("Prime Number");
            }
        } else {
            System.out.println("Composite Number");
        }
    }
}

Description:

  • This Java program checks if a number is prime. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.
  • The program uses a simple algorithm to check if a number is prime. The algorithm starts by checking if the number is 2. If the number is 2, then it is a prime number. Otherwise, the algorithm checks if the number is divisible by any number from 2 to the square root of the number. If the number is divisible by any of these numbers, then it is not a prime number. Otherwise, the number is a prime number. 
  • The program is written in Java and can be run in any Java IDE.

Post a Comment

0 Comments