Prime Factorization in Java: Explanation & Practice

Find all prime factors of a number

Problem summary

Write a program that prints all prime factors of a given number.

Starter code

public class Main {
    public static void main(String[] args) {
        int n = 12; // Test case 1
        
        // Print prime factors space-separated
        // Print: 2 2 3
    }
}

Expected output and test cases

  • 12 = 2×2×3
    2 2 3
  • 30 = 2×3×5
    2 3 5
  • 7 is prime
    7

Hints

  1. Start with smallest prime (2)
  2. Divide while divisible, then increment
  3. Continue until n becomes 1

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler