Print Prime Factors
In this step, you will enhance the prime factorization program to provide more detailed and formatted output of prime factors. We'll modify the existing prime_factorization.c
file to improve the presentation of results.
Open the file:
cd ~/project
nano prime_factorization.c
Update the code with an improved factorization function:
#include <stdio.h>
void factorize(int number) {
int original_number = number;
int factor_count = 0;
printf("Prime Factorization of %d:\n", original_number);
printf("---------------------\n");
// Start with the smallest prime number
for (int divisor = 2; divisor <= number; divisor++) {
int current_factor_count = 0;
while (number % divisor == 0) {
number /= divisor;
current_factor_count++;
factor_count++;
}
// Print factors with their exponents
if (current_factor_count > 0) {
printf("%d^%d ", divisor, current_factor_count);
}
}
printf("\n\nTotal number of prime factors: %d\n", factor_count);
}
int main() {
int number;
printf("Enter a positive integer to factorize: ");
scanf("%d", &number);
// Check for valid input
if (number <= 1) {
printf("Please enter a number greater than 1.\n");
return 1;
}
factorize(number);
return 0;
}
Key improvements in this version:
- Added formatting to display prime factors
- Shows the exponent of each prime factor
- Counts the total number of prime factors
- Preserves the original input number for display
Compile and run the program:
gcc prime_factorization.c -o prime_factorization
./prime_factorization
Example outputs:
Enter a positive integer to factorize: 24
Prime Factorization of 24:
---------------------
2^3 3^1
Total number of prime factors: 4
Enter a positive integer to factorize: 100
Prime Factorization of 100:
---------------------
2^2 5^2
Total number of prime factors: 4