Home / Programs / Java Program - Prime Factorization
Programming Example

Java Program - Prime Factorization

👁 114 Views
💻 Practical Program
📘 Step by 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;
            }
        }
    }
}

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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.