Created
June 22, 2024 21:27
-
-
Save Jammyjamjamman/6b73961529d055acaedea3ee7ed8704b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> // Include stdlib for malloc and free | |
#include <limits.h> | |
#include <stdbool.h> | |
#include <string.h> | |
void sieve_of_eratosthenes(unsigned long n) { | |
// Dynamically allocate memory for the prime array on the heap | |
bool *prime = (bool *)malloc((n + 1) * sizeof(bool)); | |
if (!prime) { | |
fprintf(stderr, "Memory allocation failed\n"); | |
exit(1); // Exit the program if memory allocation fails | |
} | |
// Initialize all entries as true | |
memset(prime, true, (n + 1) * sizeof(bool)); | |
// 0 and 1 are not prime numbers | |
prime[0] = prime[1] = false; | |
// Start from the first prime number, which is 2 | |
for (unsigned long p = 2; p * p <= n; p++) { | |
// If prime[p] is not changed, then it is a prime | |
if (prime[p]) { | |
// Update all multiples of p | |
for (unsigned long i = p * p; i <= n; i += p) | |
prime[i] = false; | |
} | |
} | |
// Print all prime numbers | |
uint min, max, count; | |
min = max = count = 0; | |
for (unsigned long p = 2; p <= n; p++) | |
if (prime[p]) { | |
min = p; | |
break; | |
} | |
for (unsigned long p = 2; p <= n; p++) | |
if (prime[p]) { | |
max = p; | |
count++; | |
} | |
printf("min: %u max: %u count: %u\n", min, max, count); | |
// Free the allocated memory | |
free(prime); | |
} | |
int main() { | |
unsigned long max_value = UINT_MAX; // Maximum value of unsigned 32-bit int | |
printf("Prime numbers up to %u are: ", max_value); | |
sieve_of_eratosthenes(max_value); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment