Computer Programming Contest Library

[Isaac's Home Page ]  [Fun Page ]  [Class Page ]  [Printable ]  
 Home
 Problem Archive
 Grades
 Tools
 Music
 

Sieve of Eratosthenes

This is an eaxmple of the Sieve of Eratosthenes.

#define MAX_NUMBER (2904)
#define MAX_SIZE ((MAX_NUMBER+15) / 16)

int sieve[MAX_SIZE];
/*
int masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};
int invMasks[8] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f};
*/
int masks[8] = {128, 64, 32, 16, 8, 4, 2, 1};
int invMasks[8] = {0x7f, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd, 0xfe};

int prime(int i)
 { /* BEGIN FUNCTON prime */
    int i1;
    int idx;
    int bit;
    int toReturn;

    /* is it even */
    if (0 == (1 & i))
        toReturn = (1 == 0);
     else
      { /* now check the odd numbers */
    /* figure out which bit belongs to current number */
    /* shift right 1 to divide by 2 because we skip even numbers */
    /* subtract 1 because we use 0-based indexing */
        i1 = (i >> 1) - 1;
        idx = i1 >> 3;
        bit = i1 & 7;
        toReturn = (0 != (sieve[idx] & masks[bit]));
      } /* now check the odd numbers */
     return toReturn;
 } /* END FUNCTON prime */

void initSieve()
 { /* BEGIN FUNCTON initSieve */
    int i;
    int i1;
    int n;
    int t;
    int idx;

    /* turn on all bits */
    for (i=0; i < MAX_SIZE; i++) sieve[i] = 0xffff;
    
    /* loop for each odd number */
    for (i=3; MAX_NUMBER>i; i=i+2)
     { /* loop for each possibe prime */
        if (prime(i))
         { /* number is prime */
printf("%d\n", i);
            n = (i >> 1) - 1;
            idx = n >> 3;
            while (MAX_SIZE > idx)
             { /* while more numbers */
                n = (n & 7) + i;
                t = n >> 3;
                if (0 < t)
                 { /* move to another word */
                    idx = idx + t;
                    n = n & 7;
                 } /* move to another word */
                sieve[idx] = sieve[idx] & invMasks[n];
               //  printf("i=%d  test=%d idx=%d   n=%d   sieve=%x\n", i, (((idx*8)+n)*2)+3, idx, n, sieve[idx]);
             } /* while more numbers */
         } /* number is prime */
     } /* loop for each possibe prime */
 } /* END FUNCTON initSieve */





[ Powered by Red Hat Linux ] [ Powered by Apache ] [ Powered by PHP ]

The statements and opinions included in these pages are those of only. Any statements and opinions included in these pages are not those of Louisiana State University or the LSU Board of Supervisors.
© 1999, 2000, 2001, 2002, 2003 Isaac Traxler