summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOskari Timperi <oskari.timperi@iki.fi>2013-02-13 22:50:37 +0200
committerOskari Timperi <oskari.timperi@iki.fi>2013-02-13 22:50:37 +0200
commitbe156b1d03acb4e3547f16601bdca1d6fd69c161 (patch)
tree461269788ed3fe1acb751d0ce75e678cd83d1868
parent4879dffd9dc5c955087c41ddc87221fb3dbb9303 (diff)
downloadeuler-c-be156b1d03acb4e3547f16601bdca1d6fd69c161.tar.gz
euler-c-be156b1d03acb4e3547f16601bdca1d6fd69c161.zip
add a very simple prime generator that uses sieve of Eratosthenes
-rw-r--r--primegen.c69
1 files changed, 69 insertions, 0 deletions
diff --git a/primegen.c b/primegen.c
new file mode 100644
index 0000000..045c2e5
--- /dev/null
+++ b/primegen.c
@@ -0,0 +1,69 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <string.h>
+
+int main(int argc, char **argv)
+{
+ int opt;
+ const char *optstr = "n:";
+ long count = -1;
+ int current, i, primecount = 0;
+
+ while ((opt = getopt(argc, argv, optstr)) != -1)
+ {
+ switch (opt)
+ {
+ case 'n':
+ count = strtol(optarg, NULL, 0);
+ break;
+
+ case '?':
+ exit(1);
+ }
+ }
+
+ if (count <= 0)
+ {
+ exit(1);
+ }
+
+ char *sieve = malloc(sizeof(char) * count);
+ memset(sieve, 1, sizeof(char) * count);
+
+ current = 2;
+
+ while (current < count)
+ {
+ if (sieve[current])
+ {
+ primecount++;
+
+ for (i = current*2; i < count; i+=current)
+ {
+ sieve[i] = 0;
+ }
+ }
+
+ current++;
+ }
+
+ printf("const long prime_table[%d] = { 2", primecount);
+
+ for (i = 3; i < count; ++i)
+ {
+ if (sieve[i])
+ {
+ printf(",%d", i);
+ }
+ }
+
+ printf("\n};\n");
+
+ printf("const long prime_table_size = %d;\n", primecount);
+
+ free(sieve);
+
+ return 0;
+} \ No newline at end of file