Мне поручено создать вектор чисел 'x' и найти простые числа в этом векторе, используя "Сито Эратосфена". Я перебрал вектор, чтобы заменить все не простые элементы на ноль. Затем я сделал цикл for, чтобы стереть все нули. Цикл стер большую часть нулей, но пропустил некоторые
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] << ", ";
}
Вывод, который я получаю:
Новый Вектор это:
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, Программа завершилась с кодом выхода: 0