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 #ifdef __Z88DK
50    #include <intrinsic.h>
51    #ifdef PRINTF
52       #pragma output CLIB_OPT_PRINTF = 0x02
53    #endif
54 #endif
55 
56 unsigned char flags[SIZE];
57 
main()58 main()
59 {
60    STATIC unsigned int i, i_sq, k, count;
61 
62    // some compilers do not initialize properly
63 
64    memset(flags, 0, SIZE);
65 
66 TIMER_START();
67 
68    count = SIZE - 2;
69 
70    i_sq = 4;
71    for (i = 2; i_sq < SIZE; ++i)
72    {
73       if (!flags[i])
74       {
75          for (k = i_sq; k < SIZE; k += i)
76          {
77             count   -= !flags[k];
78             flags[k] = 1;
79          }
80       }
81       i_sq += i+i+1;  // (n+1)^2 = n^2 + 2n + 1
82    }
83 
84 TIMER_STOP();
85 
86    PRINTF3("\n%u primes found in [2,%u]:\n\n", count, SIZE-1);
87    for (i = 2; i < SIZE; ++i)
88       if (!flags[i]) PRINTF2("%u ", i);
89 }
90