Composite Check in Java
Detect a composite number in Java by searching for a divisor with % up to i <= n / i. A match ends the loop early; zero and one are not composite.
1import java.util.Scanner;23public class Main {4 private static boolean isComposite(int n) {5 if (n <= 3) return false;6 for (int i = 2; i <= n / i; i++) {7 if (n % i == 0) return true;8 }9 return false;10 }1112 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();1617 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}
Sample Output
Enter a number: 12 12 is Composite
The helper tests i=2 and finds 12 % 2 = 0. It returns true without checking further divisors.
In this one
- Define a composite number
- Stop on the first extra divisor
- Keep neither-prime-nor-composite cases separate
How it works
- 1
Read n.
- 2
Return false for n <= 3.
- 3
Try each i from 2 to the square-root limit.
- 4
Return true for a divisor, otherwise false at the end.
Edge cases
Input one
Enter 1
It is not composite, but that does not mean it is prime.
Square of a prime
Enter 9
Trial divisor 3 is included, so 9 is composite.
What's going on
A composite number is a whole number greater than one that has a positive divisor other than one and itself. This test is a useful partner to the prime exercise, but remember that not every non-prime number is composite: zero and one are neither.
Scanner is the keyboard reader. The helper immediately rejects inputs at most 3. It then tries divisors from 2 through the square-root limit. A divisor is a value that divides the input exactly, so n % i == 0 is the test. % gives the amount left after division.
Finding just one divisor returns true and stops the search. With 12, i = 2 succeeds immediately. If every trial fails, the helper returns false. The loop uses i <= n / i instead of squaring i, keeping the limit safe for large positive int inputs. Do not print Prime as the opposite result unless you also rule out zero, one, and negatives.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Is 12 composite?
Pick an answer to check it.
Question 2
Which number is neither prime nor composite?
Pick an answer to check it.
Questions people ask
Is every even number composite?
Every even whole number greater than 2 is composite. Two is prime.
Why return after the first factor?
One extra factor is enough to establish the definition.
Does not composite always mean prime?
No. Zero, one, and negative values are also not composite under this definition.