Skip to content

Instantly share code, notes, and snippets.

@Denton-L
Last active August 29, 2015 14:26
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 Denton-L/e05e7bcf530aadf59845 to your computer and use it in GitHub Desktop.
Save Denton-L/e05e7bcf530aadf59845 to your computer and use it in GitHub Desktop.
Generates all prime numbers less than 1000000 using the Sieve of Eratosthenes.
#include <stdlib.h>
/*
* returns an int[] where int[0] is the length of the array
* and subsequent elements are the primes themselves.
*/
int* findprimes(int range) {
int prime = 2;
int i;
int *notprime = calloc(sizeof(notprime), range);
notprime[0] = notprime[1] = 1;
while (prime * prime < range) {
for (i = 2; i * prime < range; i++)
notprime[i * prime] = 1;
while (notprime[++prime])
;
}
prime = 0;
for (i = 0; i < range; i++) {
if (!notprime[i])
prime++;
}
notprime[0] = prime + 1;
prime = 1;// prime now acts as a ptr for unfilled space
for (i = 1; i < range; i++) {
if (!notprime[i]) {
notprime[prime++] = i;
}
}
return notprime;
}
#include <stdio.h>
int main() {
int i;
int *a = findprimes(1000000);
for (i = 1; i < a[0]; i++)
printf("%d\n", a[i]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment