Prime Factors of a Number in Java Using Trial Division

⚡ Direct Answer & Key Takeaway

Prime factorization breaks an integer greater than `1` into prime divisors whose product reconstructs the original number. A `for` loop tests divisors `d` from `2` while `d <= rem / d`. Whenever `rem % d == 0`, an inner `while` loop prints `d` and reduces `rem /= d` until `d` stops dividing `rem`. Stripping smaller factors first ensures every divisor printed is prime, and any remaining `rem > 1` becomes the final prime factor.

1. Why Composite Divisors Never Get Printed

A common doubt when writing trial division is how `d` avoids printing composite numbers like `4`, `6`, or `9` without calling a separate `isPrime()` helper method. Notice what happens inside the inner `while (rem % d == 0)` loop: when `d = 2`, the code divides out every factor of `2` completely before `d` increments to `3`. By the time `d` reaches `4`, `rem` is already odd and cannot be divisible by `4`. Similarly, removing all factors of `3` blocks `6` and `9` later. Thus, only genuine primes ever satisfy `rem % d == 0`.

  • Stripping `2` first prevents `4`, `8`, or `12` from dividing `rem`.
  • Stripping `3` next prevents `6`, `9`, or `15` from passing the check.
  • No helper function or extra boolean flag is needed to test primality.

2. Tracing 360 and Handling the Leftover Prime

Walk through `n = 360` to see both the inner `while` reduction and the post-loop check in action. At `d = 2`, the inner loop extracts `2` three times (`360 -> 180 -> 90 -> 45`). At `d = 3`, `rem = 45` divides twice (`45 -> 15 -> 5`), printing `3` and `3`. When `d` increments to `4`, the loop condition `4 <= 5 / 4` (`4 <= 1`) evaluates to false and terminates immediately. Without the trailing `if (rem > 1)` statement, the factor `5` would vanish silently! That final check is essential whenever the largest prime factor exceeds the square root of the reduced number.

  • At `d = 2`: prints `2 2 2`, reduces `rem` from `360` to `45`, `count = 3`.
  • At `d = 3`: prints `3 3`, reduces `rem` from `45` to `5`, `count = 5`.
  • Post-loop `if (rem > 1)`: prints `5` and raises `count` to `6`.

3. Adapting Prime Factorization for Smith and Sphenic Numbers

ICSE Board papers rarely ask for prime factors in isolation; instead, prime factorization forms the backbone of composite-number problems like Smith Numbers and Sphenic Numbers. Instead of printing `d` directly, you can accumulate `sumOfPrimeDigits` inside the inner `while` loop by adding the digit sum of `d` each time it divides `rem`. Using `d <= rem / d` avoids integer overflow when `n` approaches `Integer.MAX_VALUE`. Always reject inputs `<= 1` cleanly, because `0` and `1` have no prime factors under standard arithmetic rules.

  • Reusable core for ICSE Smith Number (`sumDigits == sumPrimeFactorDigits`).
  • Tracks factor multiplicity via `count`, helpful for Sphenic Number checks.
  • Guards `n <= 1` cleanly because `1` is neither prime nor composite.

4. PrimeFactors.java (Square-Root Bound Trial Division)

import java.util.*;

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

        if (n <= 1) {
            System.out.println("No prime factors exist for " + n);
        } else {
            int rem = n;
            int count = 0;
            System.out.print("Prime factors of " + n + ": ");
            for (int d = 2; d <= rem / d; d++) {
                while (rem % d == 0) {
                    System.out.print(d + " ");
                    rem /= d;
                    count++;
                }
            }
            if (rem > 1) {
                System.out.print(rem);
                count++;
            }
            System.out.println("\nTotal prime factors = " + count);
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter an integer (> 1): 360
Prime factors of 360: 2 2 2 3 3 5
Total prime factors = 6

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
scScannerCaptures integer input from keyboard via `System.in`
nintOriginal input integer greater than `1` (e.g., `360`)
remintRemaining unfactored quotient reduced inside loops (`360 -> 45 -> 5`)
dintTrial divisor incremented from `2` up to `rem / d` (`2 -> 3 -> 4`)
countintCounts total prime factors with multiplicity (`0 -> 3 -> 5 -> 6`)
🎯 1-on-1 Live Mentorship & Free Study Kit

Master Nested Factorization Loops Live 1-on-1

Book a 1-on-1 BlueJ coaching class to turn prime factorization into Smith Number, Sphenic Number, and prime-digit sum programs for ICSE Section B.

💬 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: Omitting the trailing if (rem > 1) block, which drops the largest prime factor whenever it exceeds the square root of the reduced quotient (e.g., 5 in 360 or 17 in 34).
  • Avoid Mistake: Using an if statement instead of an inner while loop when rem % d == 0, which prints repeated factors like 2 * 2 * 2 only once and leaves composites behind.
  • Avoid Mistake: Incrementing d inside the inner while loop or checking d <= n instead of d <= rem / d, causing missed repeats or sluggish loops on large prime inputs.
  • Examiner / Mentor Tip: Always test your factorization code on a prime number (like `29`) and a semi-prime (`26`) to verify the final `if (rem > 1)` branch works.
  • Examiner / Mentor Tip: Explain clearly in viva that dividing `rem` by `d` inside `while` is why composite divisors never appear in the output.
  • Examiner / Mentor Tip: Keep `n` untouched and operate on `rem` so you can still print or compare against the original `n` later in Smith-number questions.

7. Interactive Concept Check Quiz

Question: Suppose a student deletes the `if (rem > 1)` block at the end of the `PrimeFactors` program. What prime factors will be printed for `n = 26`?

8. Frequently Asked Questions

How does the loop skip composite divisors like 4 or 6 without an isPrime() method?
Because the inner while loop completely strips out every occurrence of smaller prime factors before d advances, no composite multiple of those primes can divide rem later. For instance, once all factors of 2 are divided out, rem becomes odd, so d = 4 can never satisfy rem % 4 == 0.
Why use d <= rem / d instead of d <= n or d * d <= rem in the for loop?
Writing d <= rem / d is mathematically equivalent to d * d <= rem for positive integers, yet it avoids integer overflow when d becomes large near Integer.MAX_VALUE. Furthermore, because rem shrinks dynamically inside the inner while loop, the upper bound tightens automatically after every factor extracted, cutting unnecessary loop iterations.
What happens if the user enters a prime number like 29 into this program?
When the input itself is prime, such as 29 or 97, the for loop finds no divisors up to its square root and exits with rem unchanged. The trailing if (rem > 1) block then prints the prime number itself once and increments count to 1, confirming it has a single prime factor.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class