//------------------------------------------------------------------- // fsieve.cpp // // This is a modification of out 'sieve.cpp' program which uses // a disk-file (instead of a memory-array) as its storage area. // // programmer: ALLAN CRUSE // written on: 12 SEP 2004 //------------------------------------------------------------------- #include // for printf(), perror(), remove() #include // for atoi(), malloc(), exit(), free() #include // for write(), lseek(), read(), close() #include // for open() #define FILEFLAGS ( O_RDWR | O_CREAT | O_TRUNC | O_SYNC ) char filename[] = "sieve.dat"; 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 ", max ); int m = 512; // default index-multiplier if ( argc > 2 ) m = atoi( argv[ 2 ] ); printf( "(index-multiplier=%d) \n", m ); // create a new disk-file for storage int fd = open( filename, FILEFLAGS, 0666 ); if ( fd < 0 ) { perror( filename ); exit(1); } // initialize the storage-area for (int i = 0; i < max; i++) { char val = ( i > 1 ) ? 1 : 0; lseek( fd, i*m, SEEK_SET ); write( fd, &val, 1 ); } // performing 'sieving' of non-primes for (int p = 0; p < max; p++) { char val; lseek( fd, p*m, SEEK_SET ); read( fd, &val, 1 ); if ( val == 0 ) continue; val = 0; for (int i = p+p; i < max; i += p) { lseek( fd, i*m, SEEK_SET ); write( fd, &val, 1 ); } } // count those integers remaining int count = 0; for (int i = 0; i < max; i++) { char val; lseek( fd, i*m, SEEK_SET ); read( fd, &val, 1 ); if ( val ) ++count; } printf( "\nNumber of primes below %d is %d \n\n", max, count ); // close the file and release its disk-space close( fd ); remove( filename ); }