Skip to content

Instantly share code, notes, and snippets.

@telendt
Created April 11, 2012 05:56
Show Gist options
  • Save telendt/2357273 to your computer and use it in GitHub Desktop.
Save telendt/2357273 to your computer and use it in GitHub Desktop.
get_prime
#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