Create a gist now

Instantly share code, notes, and snippets.

Simple prime sieve
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
if (argc != 2) {
printf("usage: genprimes num\n");
return 0;
}
int limit = atoi(argv[1]);
if (limit < 10) {
printf("the upper bound must be at least 10\n");
return 0;
}
unsigned char *sieve = (unsigned char*)calloc(sizeof(unsigned char), limit+1);
int pos;
for (pos = 2; pos < limit; pos++) {
if (sieve[pos] != 0) {
continue;
}
printf("%d\n", pos);
int i;
for (i = 2*pos; i <= limit; i += pos) {
sieve[i] = 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment