Skip to content

Instantly share code, notes, and snippets.

@zrbecker
Created April 27, 2011 01:12
Show Gist options
  • Select an option

  • Save zrbecker/943535 to your computer and use it in GitHub Desktop.

Select an option

Save zrbecker/943535 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
int nthprime(int n) {
int *primes = (int *)calloc(n, sizeof(int));
int i, count = 0;
primes[count++] = 2;
for (i = 3; count < n; ++i) {
int j, prime = TRUE;
for (j = 0; primes[j] * primes[j] <= i; ++j) {
if (i % primes[j] == 0) {
prime = FALSE;
break;
}
}
if (prime)
primes[count++] = i;
}
int result = primes[n - 1];
free(primes);
return result;
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("Usage: %s number\n", argv[0]);
return 1;
}
int n = atoi(argv[1]);
switch (n % 10) {
case 1:
printf("The %dst prime is %d.\n", n, nthprime(n));
break;
case 2:
printf("The %dnd prime is %d.\n", n, nthprime(n));
break;
case 3:
printf("The %drd prime is %d.\n", n, nthprime(n));
break;
default:
printf("The %dth prime is %d.\n", n, nthprime(n));
break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment