# Thread: extreme frustration with vectors

1. ## extreme frustration with vectors

Ok, I've tried just about everything with this tiny program I wrote, and at this point I'm nearly certain that it's failing to work simply for no reason. The point of the program is to output a certain prime number; if you type 100 and press enter, it outputs the 100th prime number. I'm not trying to find the most efficient way to handle prime numbers, i'm just doing it as an excersize in vectors, and failing miserably. Help, Please.

Code:
```#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
vector <int> primes;
primes.push_back(2);  // declaring the first couple of prime numbers
primes.push_back(3);
int quantity;
bool primestatus = true;
cin >> quantity;
int x = 2;

while (primes.size() < quantity) {
x++;

if ((x % 2) != 0) { // eliminate all even numbers right off the bat

for (int n = 0; n < (primes.size());n++) {

if ((x % primes[n]) == 0) {
primestatus = false;
break;
// if the number is divisible by any previous primes,
// then it's not prime
}
}
}
else {
primestatus = false; // even numbers get knocked out from above
}
if (primestatus == true) {
primes.push_back(x);
}
}
cout << primes[quantity] << endl;
system("PAUSE");
return EXIT_SUCCESS;
}```

2. You should explain how it is not working.

In this case, my guess is that you are never setting primestatus to true inside the loop, so once you find a non-prime number it stays false forever.

>> cout << primes[quantity] << endl;
Your use of vector looks good except for this line. At this point in the code, quantity is equal to the vector's size, and that is not a valid index. Arrays and vectors have 0-based indices, os only 0 to size-1 are valid. If quantity is 100, then primes[quantity-1] is the 100th prime.

Popular pages Recent additions