Question: The given code uses a binary search to determine if input N is a prime number. Modify the code to do the following: 1) Write

The given code uses a binary search to determine if input N is a prime number. Modify the code to do the following:

1) Write a function called "extract_prime()" that takes the two vector arrays holding all the random numbers and the boolean variables indicating which are primes as input and produces a new vector of just the prime numbers.

2) Write a function called "print()" which prints the contents of an array in a formatted fashion as shown below. Specifically, print 8 integers per line in a 3-character wide field with a space separating the numbers.

3) Add code that calls these two functions to output the prime numbers in their order of appearance. Then sort the data and eliminate any multiples of the same number. Output the result. Consider using "sort()" and "unique()" from STL to do the heavy lifting.

Given Code:

#include #include #include #include #include #include #include #include #include #include

using namespace std;

vector vec(1);

class isprime { public: isprime(); bool operator() (int);

private: int num; };

isprime::isprime() { vec.push_back(2); }

bool isprime::operator()(int num) { //sort the vector so that we can apply binary search sort(vec.begin(), vec.end()); //use binary search to get iterator bool ans = binary_search(vec.begin(), vec.end(), num); if (ans) { return true; } if (num < 2) { return false; } for (int i = 2; i <= sqrt(num); i++) { if (num%i == 0) { return false; } }

vec.push_back(num); return true; }

struct random{ int operator()() { int num = 0; //this will return number between 0 and 99 both inclusive num = rand() % 100; if (num == 0) num = 100; return num; } } GetRandom; int main(int argc, char *argv[]) { int N = 10, i; isprime pcheck; //check if commandline argments have been provided if (argc >= 2) { std::stringstream ss(argv[1]); ss >> N; } //set seeding to generate random numbers srand(time(0)); //declare vectors of size N vector vec_random(N); vector result(N); //push numbers in a vector generate(vec_random.begin(), vec_random.end(), GetRandom); //use transform function to generate a boolean vector indicating whether a number is prime or not transform(vec_random.begin(), vec_random.end(), result.begin(), pcheck); cout << "Sequence contains " << count(result.begin(), result.end(), 1) << " prime numbers." << endl; return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!