Prime and Composite Number Check Program in Java (ICSE)

⚡ Direct Answer & Key Takeaway

A natural number greater than 1 is Prime if it has exactly two positive divisors (1 and itself), and Composite if it has more than two divisors; integers `<= 1` (including 0, 1, and negatives) are neither prime nor composite. In Java BlueJ, handle `num <= 1` first, then run a loop from `i = 2` up to `limit = (int) Math.sqrt(num)` checking `if (num % i == 0)`, setting `isPrime = false` and breaking early.

1. Three-Way Classification: Prime, Composite, and Neither

Number theory divides integers into three distinct groups rather than two, a distinction CISCE examiners test repeatedly. Any integer `n > 1` with exactly two positive factors—`1` and `n` itself—is Prime (examples: `2, 3, 5, 7, 11, 29`). Any integer `n > 1` with three or more positive factors is Composite (examples: `4, 6, 9, 49`). Every integer `n <= 1`—including `1`, `0`, and negative numbers—is NEITHER prime nor composite, because `1` has only a single divisor and `0` is divisible by every nonzero integer. Handling `if (num <= 1)` as the very first branch prevents the classic mistake of falling through a divisor loop and declaring `1` or `-5` to be prime. Notice also that `2` is the smallest prime and the sole even prime.

  • `num <= 1`: Neither Prime nor Composite (handles 1, 0, and negatives cleanly).
  • `num > 1` with 2 divisors: Prime (`2` is the only even prime).
  • `num > 1` with >= 3 divisors: Composite (`4` is the smallest composite number).

2. Why Stopping Trial Division at Square Root Works

Every composite number `n` factors into `a * b = n` with `1 < a <= b < n`. Could both `a` and `b` exceed `sqrt(n)` simultaneously? No—if `a > sqrt(n)` and `b > sqrt(n)`, their product `a * b` would exceed `n`, a contradiction. Therefore, at least one factor must satisfy `a <= sqrt(n)`. Computing `int limit = (int) Math.sqrt(num);` once before the `for` loop reduces time complexity from `O(n)` to `O(sqrt(n))`: checking whether `999,983` is prime takes under 1,000 iterations instead of nearly a million! Remember two vital rules: use `i <= limit` (inclusive) so squares of primes like `49 = 7 * 7` are tested at `i = 7`, and never print inside the loop—wait until `isPrime` finishes evaluating across the full range.

  • Time complexity improves from O(n) to O(sqrt(n)) by capping divisors at `(int) Math.sqrt(num)`.
  • Inclusive `i <= limit` is mandatory to catch prime squares like `4, 9, 25, 49, 121`.
  • Using `break;` exits immediately upon finding the first divisor, avoiding wasted checks.

3. Dry Run Execution for Inputs 29, 49, and 1

Trace three representative inputs: `29`, `49`, and `1`. For `num = 29`: `29 <= 1` is `false`, `isPrime = true`, and `limit = (int) Math.sqrt(29) = 5`. The loop tests `i = 2` (`29 % 2 = 1`), `i = 3` (`29 % 3 = 2`), `i = 4` (`29 % 4 = 1`), and `i = 5` (`29 % 5 = 4`). No divisor is found; the loop terminates with `isPrime = true` and prints `29 is a Prime number.` Next, for `num = 49`: `limit = 7`. Iterations `i = 2..6` leave nonzero remainders, then at `i = 7`, `49 % 7 == 0` sets `isPrime = false` and breaks, printing `49 is a Composite number.` Finally, for `num = 1`: `if (1 <= 1)` triggers immediately, printing `1 is NEITHER Prime nor Composite.` and closing `sc`.

  • Trace 29: limit=5 -> checks i=2,3,4,5 -> no divisor -> Prime.
  • Trace 49: limit=7 -> checks i=2..6 -> i=7 divides 49 -> isPrime=false, break -> Composite.
  • Trace 1: hits early guard `num <= 1` -> Neither Prime nor Composite.

4. PrimeCompositeCheck.java (ICSE BlueJ Program)

import java.util.Scanner;

public class PrimeCompositeCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int num = sc.nextInt();

        if (num <= 1) {
            System.out.println(num + " is NEITHER Prime nor Composite.");
            sc.close();
            return;
        }

        boolean isPrime = true;
        int limit = (int) Math.sqrt(num);

        for (int i = 2; i <= limit; i++) {
            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            System.out.println(num + " is a Prime number.");
        } else {
            System.out.println(num + " is a Composite number.");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter an integer: 29
29 is a Prime number.

Enter an integer: 49
49 is a Composite number.

Enter an integer: 1
1 is NEITHER Prime nor Composite.

5. Variable Description Table (VDT)

Variable NameData TypePurpose in Program
scScannerReads the user's integer from standard input
numintStores the input integer classified as Prime, Composite, or Neither
limitintHolds integer floor of Math.sqrt(num) as the upper bound for trial division
iintLoop divisor tested from 2 up to limit against num % i == 0
isPrimebooleanFlag initialized to true and cleared to false if any divisor divides num
🎯 1-on-1 Live Mentorship & Free Study Kit

Upgrade Your ICSE Java Logic With 1-on-1 Practice

Master O(sqrt(n)) algorithms, flag patterns, and board-style VDTs with IIT/NIT mentors at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods).

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Classifying `1` or `0` as a Prime or Composite number by omitting the `if (num <= 1)` branch before entering the divisor loop.
  • Avoid Mistake: Printing `"Prime"` inside the `else` branch of `if (num % i == 0)` inside the `for` loop, which prints output repeatedly on every non-divisor!
  • Avoid Mistake: Looping all the way to `i <= num` or `i < num` without breaking early, making large prime checks unnecessarily slow.
  • Examiner / Mentor Tip: In ICSE board papers, if the question asks to count factors (`count == 2`) vs using a boolean flag (`isPrime`), both are valid; state your logic clearly.
  • Examiner / Mentor Tip: Always mention `1` as neither prime nor composite when demonstrating edge-case testing during practical viva.
  • Examiner / Mentor Tip: Verify that `limit` is calculated once before the loop instead of calling `Math.sqrt(num)` on every iteration.

7. Interactive Concept Check Quiz

Question: Why MUST the trial-division loop condition be `i <= limit` (inclusive) when `limit = (int) Math.sqrt(num)`?

8. Frequently Asked Questions

Why is 1 neither prime nor composite?
1 has only one positive divisor (itself), whereas prime numbers require exactly two distinct positive divisors and composite numbers require more than two. Thus, 1 is neither prime nor composite.
Is 2 a prime number, and does the sqrt loop handle it?
Yes. 2 has exactly two divisors (1 and 2), making it the smallest prime number and the only even prime. In our code, `limit = (int) Math.sqrt(2) = 1`, so `i = 2 <= 1` is false, `isPrime` stays `true`, and `2` is reported Prime.
Why is it enough to check divisors only up to Math.sqrt(num)?
If a number n has a factor larger than sqrt(n), its paired factor n / d must be smaller than or equal to sqrt(n), so checking up to sqrt(n) guarantees catching every composite number.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class