
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 1000000
int spf[MAX + 1]; // smallest prime factor array
void sieve() {
for (int i = 1; i <= MAX; i++) spf[i] = i;
spf[1] = 1;
for (int i = 2; i * i <= MAX; i++) {
if (spf[i] == i) { // i is prime
for (int j = i * i; j <= MAX; j += i) {
if (spf[j] == j) spf[j] = i;
}
}
}
}
void primeFactorization(int n) {
printf("Prime factors of %d: ", n);
while (n > 1) {
printf("%d ", spf[n]);
n /= spf[n];
}
printf("\n");
}
int main() {
sieve();
int number = 999983; // example input
primeFactorization(number);
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(log n) | Once the SPF (Smallest Prime Factor) array is precomputed, the factorization of any single number n takes O(log n) time in the best case — when n has large prime factors or fewer distinct factors. |
| Average Case | O(log n) | On average, a number n has about log n prime factors. Using the SPF array, we can find and divide by these prime factors efficiently, resulting in O(log n) time complexity for factorization. |
| Worst Case | O(log n) | In the worst case, such as when n is a power of 2 or has many repeated prime factors, each division by the smallest prime factor still reduces n multiplicatively, so the number of steps is bounded by O(log n). |