/* Sieve of Eratothenes Adapted from Emily Pedersen's code by Sanjiv Bhatia Feb 1 07 */ #include #include #include #include // For use with memset #define N 100 int main() { char sieve[N]; // Array to hold sieve char * ptr; // Temporary pointer into the sieve char * last_element = sieve + N; int i; // Counter // We terminate the loop at square root of N. // Add 1 to the termination condition just to make sure of rounding. int sqrt_n = (int)(sqrt ( N )) + 1; // Set the value of each element in array to 1. // Every integer is considered to be a prime number. // The numbers that are not prime will fall through the sieve. memset ( sieve, 1, N * sizeof ( char ) ); // We want to make sure that the first two elements are not prime sieve[0] = sieve[1] = 0; // Start evaluating array content for ( i = 2; i < sqrt_n; i++ ) { // If the pointer is equal to not prime, just go to next iteration if ( ! *( ptr = sieve + i ) ) continue; // Drip all the multiples through the sieve for ( ptr += i; ptr < last_element; ptr += i ) *ptr = 0; } // Print out primes for ( ptr = sieve + 2; ptr < last_element; ptr++ ) if ( *ptr ) printf ( "%6d\n", ptr - sieve ); return ( 0 ); }