Java Program - Prime Factorization

Mathematics for Programming Numbers (Article) Numbers (Program)

21

Given Input:

56

Expected Output:

Prime factors of 56 are: 2 2 2 7

Program:

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.

This Particular section is dedicated to Programs only. If you want learn more about Mathematics for Programming. Then you can visit below links to get more depth on this subject.