Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program for efficiently print all prime factors of a given number?
In this section, we will see how we can get all the prime factors of a number in an efficient way. There is a number say n = 1092, we have to get all prime factors of this. The prime factors of 1092 are 2, 2, 3, 7, 13. To solve this problem, we have to follow this rule −
When the number is divisible by 2, then print 2, and divide the number by 2 repeatedly.
Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then print, and change the number by divide it with the current number then continue.
Let us see the algorithm to get a better idea.
Syntax
void primeFactors(int n);
Algorithm
printPrimeFactors(n)
begin
while n is divisible by 2, do
print 2
n := n / 2
done
for i := 3 to ?n, increase i by 2, do
while n is divisible by i, do
print i
n := n / i
done
done
if n > 2, then
print n
end if
end
Example
This program efficiently finds all prime factors by first dividing by 2, then checking only odd numbers up to the square root −
#include <stdio.h>
#include <math.h>
void primeFactors(int n) {
int i;
/* Handle factor 2 */
while(n % 2 == 0) {
printf("%d ", 2);
n = n / 2; /* reduce n by dividing this by 2 */
}
/* Handle odd factors from 3 onwards */
for(i = 3; i <= sqrt(n); i = i + 2) { /* i will increase by 2, to get only odd numbers */
while(n % i == 0) {
printf("%d ", i);
n = n / i;
}
}
/* If n is a prime greater than 2 */
if(n > 2) {
printf("%d ", n);
}
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Prime factors of %d are: ", n);
primeFactors(n);
printf("<br>");
return 0;
}
Enter a number: 24024 Prime factors of 24024 are: 2 2 2 3 7 11 13
How It Works
The algorithm works in three steps:
- Handle factor 2: Divide by 2 repeatedly until the number becomes odd
- Handle odd factors: Check divisibility from 3 to ?n, incrementing by 2 (only odd numbers)
- Handle remaining prime: If the remaining number is greater than 2, it's a prime factor itself
Key Points
- Time complexity is O(?n) as we only check up to the square root
- The algorithm handles even and odd factors separately for efficiency
- Any remaining number greater than 2 after the loop is guaranteed to be prime
Conclusion
This efficient prime factorization algorithm reduces the search space by handling 2 separately and checking only odd numbers up to the square root. It provides optimal performance for finding all prime factors of any given number.
