How to check if a given number is prime or not using java

import java.util.Scanner;

public class PrimeNumberChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int num = scanner.nextInt();
        boolean isPrime = checkPrime(num);
        System.out.println(num + " is " + (isPrime ? "prime" : "not prime"));
        scanner.close();
    }

    private static boolean checkPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

 

Post your Answer