Last active
August 29, 2015 14:26
-
-
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.
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 <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; | |
} |
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> | |
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