I'm tasked with creating a vector of 'x' numbers and finding the prime numbers in that vector using the "Sieve of Eratosthenes." I iterated through the vector to replace all of the non-prime elements with zero. Then I made a for loop to erase all of the zeros. The loop erased most of the zeros however it skipped some
vector<int> primes;
int userNum = 0; //variable for user to input the size of the vector
cout << "Enter your num, brah";
cin >> userNum;
for (int i = 2; i < userNum; i++) //creates a vector of numbers
{
primes.push_back(i);
}
int j = 0; //variable to find non-primes
for (int p = primes[0]; p < primes.size(); p++) //loop to replace non-primes with zeros
{
j = p+p;
while (j < (primes.size() +2)) {
replace(primes.begin(), primes.end(), j, 0);
j+= p;
}
}
for (int y = 0; y < primes.size(); y++) { //loop to erase the zeros from the vector
cout << "y1 " << primes[y] << " "; //cout simply just to find see what is going on
if (primes[y] == 0) {
primes.erase(primes.begin() +y);
cout << "y2: " << y << endl; //cout simply just to find see what is going on
}
}
cout << "New Vector is: " << endl; //loop to print the vector
for (int l = 0; l < primes.size(); l++)
{
cout << primes[l] << ", ";
}
The output I get is: New Vector is: 2, 3, 5, 7, 0, 11, 13, 0, 17, 19, 0, 23, 0, 0, 29, 31, 0, 0, 37, 0, 41, 43, 0, 47, 0, 0, 53, 0, 0, 59, 61, 0, 0, 67, 0, 71, 73, 0, 0, 79, 0, 83, 0, 0, 89, 0, 0, 0, 97, 0, Program ended with exit code: 0