// Program: Tabulate the ending digits of prime numbers. // Version: 4, uses STL vectors // Author: Chuck Stewart // Date: January, 2001 #include #include #include #include using namespace std; // Sieve, Version 4: Revised version of the primes counting program // that uses STL vectors instead of our templated array. This // includes the important member function push_back which adds primes // to the back of the array. The code assumes the primes array is // initially empty. Notice how much shorter the code is. void sieve_of_eratosthenes( int n, vector& primes ) { int i; // Define and initialize the array of bool. vector is_prime(n+1, true); // Apply the Sieve of Eratosthenes. Stop at sqrt(n) because if a // number is composite (not prime), it will have at least one // factor <= sqrt(n). for ( i=2; i<=sqrt(n)+1; ++i ) { if ( !is_prime[i] ) continue; // Skip the rest of the loop for non-primes int j; for ( j=2*i; j<=n; j+=i ) // Mark multiples of prime i to be non-prime is_prime[j] = false; } // Fill in the primes vector with the prime integers for ( i=2; i<=n; ++i ) if ( is_prime[i] ) primes.push_back( i ); } // A test driver for the Sieve of Eratosthenes function. Notice no // explicit allocation and deallocation of the int_array object is // included inside the code. void test_sieve() { int n=200; cout << "\nTesting the Sieve for n=" << n << endl; vector primes; sieve_of_eratosthenes( n, primes ); cout << primes.size() << " primes were found. Here they are.\n"; for ( int i=0; i& primes, vector& rcount ) { int i; for ( i=0; i primes; // Apply the sieve and then count the statistics. sieve_of_eratosthenes( n, primes ); vector rcount(10,0); count_remainders( primes, rcount ); // Output the results. cout << "For primes less than or equal to " << n << ",\n" << "here is the counts of the ending digits." << endl; for ( int i=0; i<10; ++i ) cout << i << ": " << rcount[i] << endl; return 0; }