Created
April 11, 2012 05:56
-
-
Save telendt/2357273 to your computer and use it in GitHub Desktop.
get_prime
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> | |
#include <assert.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <stdbool.h> | |
#include <math.h> | |
void die(const char *message) | |
{ | |
if (errno) { | |
perror(message); | |
} else { | |
printf("ERROR: %s\n", message); | |
} | |
exit(1); | |
} | |
unsigned int get_prime(unsigned int n) | |
{ | |
assert(n > 0); | |
unsigned int *const primes = malloc(sizeof(unsigned int) * n); | |
if (!primes) { | |
die("Memory error"); | |
} | |
unsigned int num = *primes = 2; | |
--n; | |
unsigned int *last = primes; | |
while (n) { | |
++num; | |
int s = sqrt(num); | |
bool is_prime = true; | |
unsigned int *i; | |
for (i = primes; *i <= s && i <= last; ++i) { | |
if (0 == num % *i) { | |
is_prime = false; | |
break; | |
} | |
} | |
if (is_prime) { | |
*(++last) = num; | |
--n; | |
} | |
} | |
free(primes); | |
return num; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
assert(2 == argc); | |
printf("%d\n", get_prime(atoi(argv[1]))); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment