more fixes/cleanups to langshootout code
[libfirm] / ir / be / test / langshootout / nsieve-bits.c
1 /*
2  * The Great Computer Language Shootout
3  * http://shootout.alioth.debian.org/
4  *
5  * Written by Dima Dorfman, 2004
6  * Compile: gcc -std=c99 -O2 -o nsieve_bits_gcc nsieve_bits.c
7  */
8
9 #include <limits.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <stdint.h>
13 #include <string.h>
14
15 typedef uint_fast8_t bits;
16 #define NBITS   (CHAR_BIT * sizeof(bits))
17
18 static uintmax_t
19 nsieve(uintmax_t m)
20 {
21         uintmax_t count, i, j;
22         bits a[m / NBITS];
23
24         memset(a, (1 << CHAR_BIT) - 1, sizeof(a));
25         count = 0;
26         for (i = 2; i < m; ++i)
27                 if (a[i / NBITS] & (1 << i % NBITS)) {
28                         for (j = i + i; j < m; j += i)
29                                 a[j / NBITS] &= ~(1 << j % NBITS);
30                         ++count;
31                 }
32         return (count);
33 }
34
35 static void
36 test(unsigned long n)
37 {
38         uintmax_t count, m;
39
40         m = (1 << n) * 10000;
41         count = nsieve(m);
42         printf("Primes up to %8ju %8ju\n", m, count);
43 }
44
45 int
46 main(int argc, char **argv)
47 {
48         unsigned long n = 9;
49         char *cp;
50
51                 if(argc > 1)
52                         n = atoi(argv[1]);
53         test(n);
54         if (n >= 1)
55                 test(n - 1);
56         if (n >= 2)
57                 test(n - 2);
58         exit(0);
59 }