Print All Prime Numbers
In this step, you will complete the Sieve of Eratosthenes implementation by printing all the prime numbers found within the given range.
Let's modify the prime_sieve.c
file to add the printing functionality:
cd ~/project
nano prime_sieve.c
Update the code to print prime numbers:
#include <stdio.h>
#include <stdbool.h>
int main() {
int upper_limit;
printf("Enter the upper limit for finding prime numbers: ");
scanf("%d", &upper_limit);
// Create a boolean array to mark prime and non-prime numbers
bool is_prime[upper_limit + 1];
// Initialize all numbers as prime
for (int i = 2; i <= upper_limit; i++) {
is_prime[i] = true;
}
// Mark multiples of each prime number as non-prime
for (int p = 2; p * p <= upper_limit; p++) {
if (is_prime[p]) {
// Mark multiples of p as non-prime
for (int i = p * p; i <= upper_limit; i += p) {
is_prime[i] = false;
}
}
}
// Print all prime numbers
printf("Prime numbers up to %d are:\n", upper_limit);
for (int p = 2; p <= upper_limit; p++) {
if (is_prime[p]) {
printf("%d ", p);
}
}
printf("\n");
return 0;
}
Compile and run the program:
gcc prime_sieve.c -o prime_sieve
./prime_sieve
Example output:
Enter the upper limit for finding prime numbers: 50
Prime numbers up to 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Let's break down the final steps:
- After marking multiples, we iterate through the
is_prime
array
- We print only the numbers that remain marked as prime
- The output shows all prime numbers up to the user-specified limit