Skip to content

Instantly share code, notes, and snippets.

@zrbecker
Created April 22, 2011 06:17
Show Gist options
  • Save zrbecker/936157 to your computer and use it in GitHub Desktop.
Save zrbecker/936157 to your computer and use it in GitHub Desktop.
Euler 7
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef unsigned long ul;
/*
* Finds the nth prime
*/
ul euler7(ul n) {
int cprimes = 10;
ul *primes = (ul *)malloc(cprimes * sizeof(ul));
int nprimes = 0;
int i, j, prime;
for (i = 2; nprimes < n; ++i) {
prime = 1;
ul max = (ul)sqrt((double)i);
for (j = 0; j < nprimes; ++j) {
if (max < primes[j])
break;
if (i % primes[j] == 0) {
prime = 0;
break;
}
}
if (prime) {
++nprimes;
if (nprimes >= cprimes) {
cprimes *= cprimes;
primes = (ul *)realloc(primes, cprimes * sizeof(ul));
}
primes[nprimes - 1] = i;
}
}
ul nth_prime = primes[nprimes - 1];
free(primes);
return nth_prime;
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("Usage: %s number\n", argv[0]);
return 1;
}
ul n = strtoul(argv[1], NULL, 0);
ul prime = euler7(n);
printf("The %luth prime is %lu.\n", n, prime);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment