Skip to content

Instantly share code, notes, and snippets.

@Prince781
Last active December 19, 2015 20:59
Show Gist options
  • Select an option

  • Save Prince781/6016807 to your computer and use it in GitHub Desktop.

Select an option

Save Prince781/6016807 to your computer and use it in GitHub Desktop.
Basic C code to get the nth prime number in a sequence.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
unsigned long nth_prime(unsigned long n) {
unsigned long p = 2, i=0, c;
while (i < n) {
unsigned long n_f = 0; // number of factors
for (c=(unsigned long)sqrt(p); c>0; c--)
n_f += (p%c==0);
i += (n_f==1); // we should only have 1 factor
p++;
}
return --p; // our prime number
}
int main(int argc, char *argv[]) {
int i=1;
for (i; i<argc; i++) {
unsigned long n;
sscanf(argv[i], "%lu", &n);
printf("Prime number at interval %lu is %lu.\n", n, nth_prime(n));
}
return 0;
}
@Prince781
Copy link
Copy Markdown
Author

Updated, since the old version was inaccurate and unnecessarily dependent on booleans.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment