Kajetan Johannes Hammerle 3 years ago
commit
99e81b95d3
3 changed files with 63 additions and 0 deletions
  1. 1 0
      .gitignore
  2. 55 0
      Main.c
  3. 7 0
      Makefile

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+primes

+ 55 - 0
Main.c

@@ -0,0 +1,55 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+char* data = NULL;
+
+int hasBit(int index) {
+    return (data[index >> 3] & (1 << (index & 7))) == 0;
+}
+
+void setBit(int index) {
+    data[index >> 3] |= (1 << (index & 7));
+}
+
+int divideRound8(int i) {
+    return (i >> 3) + ((i & 7) != 0);
+}
+
+int main(int argAmount, const char** args) {
+    if(argAmount < 2) {
+        if(argAmount > 0) {
+            printf("%s <max_prime>\n", args[0]);
+        } else {
+            puts("... <max_prime>");
+        }
+        return 0;
+    }
+    int max = atoi(args[1]);
+    if(max <= 0) {
+        puts("max prime should be a positive number");
+        return 0;
+    }
+
+    int end = (max - 1) >> 1;
+    data = calloc(divideRound8(end), 1);
+
+    int found = 0;
+    if(max >= 2) {
+        puts("2");
+        found++;
+    }
+    for(int i = 0; i < end; i++) {
+        if(hasBit(i)) {
+            long prime = (i << 1) + 3;
+            for(long k = i + prime; k < end; k += prime) {
+                setBit(k);
+            }
+            printf("%ld\n", prime);
+            found++;
+        }
+    }
+    printf("found: %d\n", found);
+
+    free(data);
+    return 0;
+}

+ 7 - 0
Makefile

@@ -0,0 +1,7 @@
+all: primes
+	
+primes: Main.c
+	gcc -o $@ Main.c -Wall -Wextra -Werror -pedantic -O3
+	
+clean:
+	rm -f primes