I am supposed to augment the code below. Im supposed to use a change the program
ID: 3734597 • Letter: I
Question
I am supposed to augment the code below. Im supposed to use a change the program so that i use a VECTOR instead of an array.
Im not sure how to to this.
Code follows below.
#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
bool prime[n+1];
memset(prime, true, sizeof(prime));
for (int p=2; p*p<=n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i=p*2; i<=n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p=2; p<=n; p++)
if (prime[p])
cout << p << " ";
}
// Driver Program to test above function
int main()
{
int n = 30;
cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
SieveOfEratosthenes(n);
return 0;
}
Explanation / Answer
First, it makes sense to define an isPrime() function to make your code more readable:
bool isPrime(int p)
{
for(int i = 2; i <= p/2; i++)
{
if(p%i == 0)
{
return false;
}
}
return true;
}
Then you can write your main() in the following way:
int main()
{
int input;
cout << "Enter a positive integer: ";
cin >> input;
// You deal with integers here, so you shouldn't use vector<double>.
// As all numbers are positive, you could also use unsigned int.
vector<int> primeHolder;
for(int i = 2; i <= input; i++)
{
if(isPrime(i))
{
// If the tested value is a prime, append it to the vector.
primeHolder.push_back(i);
}
}
cout << "There are " << primeHolder.size() << " primes:" << endl;
for(size_t j = 0; j < primeHolder.size(); j++)
{
// Print every prime number that was stored in the vector.
cout << primeHolder[j] << endl;
}
return 0;
}
Below is the output as follows:
Enter a positive integer: 10
There are 4 primes:
2
3
5
7
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.