Skip to content

Instantly share code, notes, and snippets.

@EmilHernvall
Created May 3, 2011 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmilHernvall/953776 to your computer and use it in GitHub Desktop.
Save EmilHernvall/953776 to your computer and use it in GitHub Desktop.
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