Check Whether Input Number Is Prime Or Not | Java Programs

Output:

*** Check For Any Prime Number ***

Enter any number: 7895462
7895462 is not a Prime Number
-----------------------------------
*** Check For Any Prime Number ***

Enter any number: 784129
784129 is a Prime Number

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

public class CheckPrime {

    public static void main(String args[]) {
        int temp;
        boolean isPrime = true;
        Scanner scan = new Scanner(System.in);
        System.out.println("*** Check For Any Prime Number ***" + "\n");
        System.out.print("Enter any number: ");
        int num = scan.nextInt();
        for (int i = 2; i <= num / 2; i++) {
            temp = num % i;
            if (temp == 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
            System.out.println(num + " is a Prime Number");
        } else {
            System.out.println(num + " is not a Prime Number");
        }
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon