Problem:- Write a number program to check whether a number is prime or not in Java?
Solution:- Let's see 1st what is a prime number. A number that is greater than 1 and divisible by either 1 or itself only is called a Prime number. For example:- 5 will be divided by only 1 and 5. So, 5 is a prime number.
Java code:-
package com.codeforsolution.java.logical;
import java.util.InputMismatchException;import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter a number to check prime or not"); int num; try { num = s.nextInt(); if(isPrime(num)) { System.out.println(num +" is a Prime number"); } else { System.out.println(num + " is not a prime number"); } } catch (InputMismatchException e) { System.out.println("Please enter a valid number"); } s.close(); }
private static boolean isPrime(int num) { if(num <= 1) { return false; } else { for(int i=2; i<= num/2; i++) { if((num%i)==0) { return false; } } } return true; }
}
Output:-
Enter a number to check prime or not
12
12 is not a prime number
Enter a number to check prime or not
11
11 is a Prime number