Last active
December 19, 2015 20:59
-
-
Save Prince781/6016807 to your computer and use it in GitHub Desktop.
Basic C code to get the nth prime number in a sequence.
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
| #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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated, since the old version was inaccurate and unnecessarily dependent on booleans.