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 "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.
Given Code:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#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
vector
//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
Get step-by-step solutions from verified subject matter experts
