
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 <stdbool.h>
#include <string.h>
void sieveOfEratosthenes(int n) {
bool isPrime[n+1];
memset(isPrime, true, sizeof(isPrime));
isPrime[0] = false;
isPrime[1] = false;
for (int p = 2; p*p <= n; p++) {
if (isPrime[p]) {
for (int i = p*p; i <= n; i += p) {
isPrime[i] = false;
}
}
}
printf("Prime numbers up to %d: ", n);
for (int i = 2; i <= n; i++) {
if (isPrime[i]) printf("%d ", i);
}
printf("\n");
}
int main() {
int n = 50;
sieveOfEratosthenes(n);
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n log log n) | The Sieve of Eratosthenes runs in O(n log log n) time in all cases because it only marks multiples of primes starting from 2 up to sqrt(n). This is the most efficient known complexity for generating all primes up to n using this method. |
| Average Case | O(n log log n) | Regardless of the input value of n, the average case involves marking off multiples of prime numbers, resulting in approximately O(n log log n) operations. |
| Worst Case | O(n log log n) | The worst case still follows the same process of iterating through multiples of primes, up to sqrt(n), and marking them. This results in O(n log log n) time complexity even in the worst case. |