Composite Check in Java

Check whether a given number is composite.

IntermediateModule 3: Loop ProgramsExample 22 of 25
composite-check.java
1import java.util.Scanner;
2
3public class Main {
4 private static boolean isComposite(int n) {
5 if (n <= 3) return false;
6 for (int i = 2; i * i <= n; i++) {
7 if (n % i == 0) return true;
8 }
9 return false;
10 }
11
12 public static void main(String[] args) {
13 Scanner sc = new Scanner(System.in);
14 System.out.print("Enter a number: ");
15 int n = sc.nextInt();
16
17 if (isComposite(n)) {
18 System.out.println(n + " is Composite");
19 } else {
20 System.out.println(n + " is not Composite");
21 }
22 sc.close();
23 }
24}

Output

Enter a number: 12
12 is Composite

What's going on

Composite numbers have at least one divisor other than 1 and themselves; we search for such a divisor.