1 /*
2 * COMMAND LINE DEFINES
3 *
4 * -DSIZE=N
5 * Investigate numbers 2..N-1 for primes.
6 *
7 * -DSTATIC
8 * Use static variables instead of locals.
9 *
10 * -DPRINTF
11 * Enable printf.
12 *
13 * -DTIMER
14 * Insert asm labels into source code at timing points.
15 *
16 */
17
18 #ifndef SIZE
19 #define SIZE 8000
20 #endif
21
22 #ifdef STATIC
23 #undef STATIC
24 #define STATIC static
25 #else
26 #define STATIC
27 #endif
28
29 #ifdef PRINTF
30 #define PRINTF2(a,b) printf(a,b)
31 #define PRINTF3(a,b,c) printf(a,b,c)
32 #else
33 #define PRINTF2(a,b)
34 #define PRINTF3(a,b,c)
35 #endif
36
37 #ifdef TIMER
38 #define TIMER_START() intrinsic_label(TIMER_START)
39 #define TIMER_STOP() intrinsic_label(TIMER_STOP)
40 #else
41 #define TIMER_START()
42 #define TIMER_STOP()
43 #endif
44
45
46 #include <stdio.h>
47 #include <string.h>
48
49 unsigned char flags[SIZE];
50
main()51 main()
52 {
53 STATIC unsigned int i, i_sq, k, count;
54
55 /* some compilers do not initialize properly */
56
57 memset(flags, 0, SIZE);
58
59 TIMER_START();
60
61 count = SIZE - 2;
62
63 i_sq = 4;
64 for (i = 2; i_sq < SIZE; ++i)
65 {
66 if (!flags[i])
67 {
68 for (k = i_sq; k < SIZE; k += i)
69 {
70 count -= !flags[k];
71 flags[k] = 1;
72 }
73 }
74 i_sq += i+i+1; /* (n+1)^2 = n^2 + 2n + 1 */
75 }
76
77 TIMER_STOP();
78
79 PRINTF3("\n%u primes found in [2,%u]:\n\n", count, SIZE-1);
80 for (i = 2; i < SIZE; ++i)
81 if (!flags[i]) PRINTF2("%u ", i);
82 }
83