// Program: Tabulate the ending digits of prime numbers. // Version: 3, uses our templated array class // Author: Chuck Stewart // Date: January, 2001 #include #include #include using namespace std; #include "t_array.h" // Revised version of the primes counting program that uses the // templated array class wherever there is an array. void sieve_of_eratosthenes( int n, t_array& primes ) { int i; // Define and initialize the array of bool. Look below to see that // explicit deletion of the is_prime array is not needed. t_array 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; } // Count the primes int count = 0; for ( i=2; i<=n; ++i ) if ( is_prime[i] ) count ++ ; // Tell the primes object how much space is needed to store the // primes and then store the primes. primes.resize( count ); int k=0; for ( i=2; i<=n; ++i ) if ( is_prime[i] ) { primes[k] = i; k ++ ; } } // 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; t_array primes; sieve_of_eratosthenes( n, primes ); cout << primes.size() << " primes were found. Here they are.\n" << primes << endl; } // A function to gather the statistics on the number of primes that // end in each digit. Notice that the primes object is passed by // reference, but it is a const. Passing by reference prevents the // expense of calling the copy constructor, while making it a const // means only const member functions may be called. The rcount // object is passed by reference because it must be modified. void count_remainders( const t_array& primes, t_array& rcount ) { int i; for ( i=0; i primes; // Apply the sieve and then count the statistics. sieve_of_eratosthenes( n, primes ); t_array 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; }