Skip to content

Instantly share code, notes, and snippets.

@nekodjin
Created January 3, 2022 16:03
Show Gist options
  • Save nekodjin/7a38c220c2ee604d110fac0bc69cc951 to your computer and use it in GitHub Desktop.
Save nekodjin/7a38c220c2ee604d110fac0bc69cc951 to your computer and use it in GitHub Desktop.
Simple, portable, and (mostly) UB-free implementation of the Sieve of Eratosthenes in C99
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#define u8 uint8_t
#define u32 uint32_t
int main(void) {
u8 *arr;
u32 i, j, x, c;
printf("Enter a number: ");
if (1 != scanf("%"SCNu32, &x)) {
puts("Could not parse integer literal.");
return 1;
}
arr = malloc(x * sizeof(*arr));
if (NULL == arr) {
puts("Not enough memory to calculate requested range.");
return 1;
}
puts("Calculating...");
c = 0;
arr[0] = 0;
for (i = 1; i < x; i++) {
arr[i] = 1;
}
for (i = 2; i <= x; i++) {
if (0 == arr[i-1]) continue;
for (j = i*2; j <= x; j += i) {
arr[j-1] = 0;
}
c++; // hehe
}
printf("Found %"PRIu32" primes. List them all? (y/N) ", c);
// because nobody uses [LF]CR anymore
while ('\n' != getchar());
if ('y' != getchar()) return 0;
for (i = 0; i < x; i++) {
if (arr[i]) {
printf("%"PRIu32"\n", i+1);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment