Home / Programs / Java Program - Prime Factorization
🚀 Programming Example

Java Program - Prime Factorization

👁 114 Views
💻 Practical Program
📘 Step Learning

This program performs prime factorization of a given number.

📌 Information & Algorithm

Given Input:

56

Expected Output:

Prime factors of 56 are: 2 2 2 7

💻 Program Code

public class PrimeFactorization {
    public static void main(String[] args) {
        int number = 56;
        System.out.print("Prime factors of " + number + " are: ");
        for (int i = 2; i <= number; i++) {
            while (number % i == 0) {
                System.out.print(i + " ");
                number /= i;
            }
        }
    }
}

                        

🖥 Program Output

Prime factors of 56 are: 2 2 2 7
                            

📘 Explanation

  • Initialization:

    • int number = 56;: The number to be factorized is initialized to 56.
  • Prime Factorization Process:

    • for (int i = 2; i <= number; i++): This loop iterates through all numbers starting from 2 up to the given number.
    • while (number % i == 0): This inner loop checks if i is a factor of number. If number is divisible by i (i.e., number % i == 0), it means i is a prime factor.
    • System.out.print(i + " ");: If i is a factor, it is printed as a prime factor.
    • number /= i;: The value of number is divided by i. This reduces number by removing the factor i and allows the loop to check for other factors.
  • Output:

    • The program prints all prime factors of the number. For 56, the output will be 2 2 2 7, indicating that 56 = 2 * 2 * 2 * 7.

How It Works:

  • The program starts by checking the smallest prime number (2) and continues to check all integers up to the given number.
  • For each integer, it repeatedly divides the number if the integer is a factor, printing each prime factor as it is found.
  • The process continues until all prime factors are found and printed.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.