Question: The given code checks each input number to see whether it is prime or not. Modify the code to do the following: 1) Change isprime::operator()
The given code checks each input number to see whether it is prime or not. Modify the code to do the following:
1) Change "isprime::operator()" to use a binary search instead of the linear search implemented by "checklist()" to determine if input N is a prime number. You are encouraged to use "binary_search()" from STL to do the job. Note that this algorithm returns a boolean that indicates whether the number N was found or not.
2) Now change the driver code in the main program. First, have it use an optional command line argument to set the number of integers to test. Call this number N. If no command line argument is present, use N=123 as the default. Seed the random number generator with N. See the "clibstd" family of functions for "srand()". Second, generate a list of N random numbers in the range 1-140. As a suggestion, write a function object for producing each random number using "rand()" while letting "generate()" from STL fill in the list. Feel free to represent the list using a "vector" which you may recall is an array-based sequence container. Third, use "transform()" from STL along with function object "isprime" to obtain a boolean array that indicates which random number is prime. Feed this array to "count()" from STL to determine how many prime numbers there are.
Given Code: #include
class isprime {
vector
return listPrimes.back(); } void expand(int N) {
for(int i = listPrimes.back() + 1; i <= N+1; i++) {
if(isPrime(i)) { listPrimes.push_back(i); } } } bool checkList(int x) {
//Linear search for integer in list of primes already stored for(int i=0; i < listPrimes.size(); i++) {
if(listPrimes[i] == x) return true; } return false; }
bool isPrime(int x) {
for(int i =2; i <= sqrt(x); i++) {
if(x%i == 0) //Return false at first instance where x%i == 0 return false; } return true; }
}; int main() {
int n; isprime p; while(cin >> n) {
//If the number entered is larger than the largest prime stored, we expand the list if(p.largestPrime() < n) {
p.expand(n); } //Check if n is present in list of primes if(p.checkList(n)) cout<
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
