Skip to content

Prime or Not

Check if a number is prime using a loop.

package DSA.Flow_control;
import java.util.Scanner;
public class primeornot {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter a Number");
int n = sc.nextInt();
if (n == 2 || n == 1) {
System.out.println("Prime");
} else {
boolean p = true;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
p = false;
}
}
if (p == true) {
System.out.println("Prime");
} else {
System.out.println("Not Prime");
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}