Created
May 21, 2015 03:34
-
-
Save derekli66/36d712c9b5d0f14abfae to your computer and use it in GitHub Desktop.
Programming exercise 6-4 in book, Pointers on C.
This file contains hidden or 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
void FindPrimeNumber(int size, int results[]) { | |
// create elements array | |
int *elements; | |
elements = (int *)malloc(size * sizeof(int)); | |
for (int i = 0; i < size ; i++) { | |
elements[i] = 1 ; | |
} | |
//start to cross out. Beginning from i = 2 | |
for (int i = 2; i < size + 2; i++) { | |
int j = i * 2; | |
while (j < size + 2) { | |
elements[j - 2] = 0 ; | |
j += i; | |
} | |
} | |
// put all prime number into results array | |
int counter = 0; | |
for (int i = 2; i < size + 2 ; i++) { | |
if (elements[i - 2] == 1) { | |
results[counter] = i; | |
counter++; | |
} | |
} | |
} | |
int main(int argc, const char * argv[]) { | |
int *results; | |
results = (int *)malloc(1000 * sizeof(int)); | |
for (int i = 0; i < 1000; i++) { | |
results[i] = '\0'; | |
} | |
FindPrimeNumber(1000, results); | |
for (int i = 0; i < 1000; i++) { | |
if (results[i] == '\0') break; | |
printf("Prime number: %d\n", results[i]); | |
} | |
free(results); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment