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
using namespace std;
vector
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
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started