//------------------------------------------------------------------- // sieve.cpp // // This program implements a version of the famous Prime Number // Sieve algorithm, credited to the ancient Greek mathematician // Erastosthenes (circa 250 B.C.). We will use some variations // of this program to study data-access timings and the effects // of caches used by the processor and by the operating system. // // programmer: ALLAN CRUSE // written on: 12 SEP 2004 //------------------------------------------------------------------- #include // for printf(), perror() #include // for atoi(), malloc(), exit(), free() int main( int argc, char **argv ) { int max = 400000; // default array-size if ( argc > 1 ) max = atoi( argv[ 1 ] ); printf( "\ncounting prime numbers below %d \n", max ); // allocate array-storage char *array = (char*)malloc( max ); if ( !array ) { perror( "malloc" ); exit(1); } // initialize the array for (int i = 0; i < max; i++) array[ i ] = ( i > 1 ) ? 1 : 0; // perform 'sieving' of non-primes for (int p = 0; p < max; p++) { if ( array[ p ] == 0 ) continue; for (int i = p+p; i < max; i += p) array[ i ] = 0; } // count those integers remaining int count = 0; for (int i = 0; i < max; i++) if ( array[ i ] ) ++count; printf( "\nNumber of primes below %d is %d \n\n", max, count ); // release allocated array-storage free( array ); }