IN C++, WILL UPVOTE CORRECT SOLUTIONS ASAP! Need 5-7 done SEPERATELY 5. Change t
ID: 3756685 • Letter: I
Question
IN C++, WILL UPVOTE CORRECT SOLUTIONS ASAP!
Need 5-7 done SEPERATELY
5. Change the array type to bool and comment on changes to run time. Be sure to use types char and bool in your testing.
6. Change the static array in to a dynamic array and compare the run times
7. Change the static array in to a vector and compare the run times
CODE:
#include <iostream>
#include <ctime>
using namespace std;
static const int N = 1000;
int main()
{
int i;
char a[N];
clock_t begin = clock();
for (i = 2; i < N; i++)
a[i] = 1;
for (i = 2; i < N; i++){
if (a[i])
for (int j = i; j*i < N; j++) a[i*j] = 0;
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
int k= 0;
for (i = 2; i < N; i++){
if (a[i]) {
k++;
cout << " " << i;
}
if(k==10){
cout<<endl;
k= 0;
}
}
}
Explanation / Answer
Making array dynamic
#include <iostream>
using namespace std;
int main()
{
int N;
cout<<"Enter value of N : "; //Change that needs to be done to make the array dynamic
cin>>N;
int i, a[N];
for (i = 2; i < N; i++)
a[i] = 1;
for (i = 2; i < N; i++)
if (a[i])
for (int j = i; j*i < N; j++)
a[i*j] = 0;
for (i = 2; i < N; i++)
if (a[i]) cout << " " << i;
cout << endl;
}
7. By using vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int N;
cout<<"Enter value of N : "; //Change that needs to be done to make the array dynamic
cin>>N;
int i;
vector<int> a(N);
for (i = 2; i < N; i++)
a[i] = 1;
for (i = 2; i < N; i++)
if (a[i])
for (int j = i; j*i < N; j++)
a[i*j] = 0;
for (i = 2; i < N; i++)
if (a[i]) cout << " " << i;
cout << endl;
}