Java Program - Prime Factorization
This program performs prime factorization of a given number.
This program performs prime factorization of a given number.
56
Prime factors of 56 are: 2 2 2 7
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;
}
}
}
}
Prime factors of 56 are: 2 2 2 7
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:
56, the output will be 2 2 2 7, indicating that 56 = 2 * 2 * 2 * 7.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.
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.