Programming Example
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 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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.