Thread: extreme frustration with vectors

  1. #1
    irregularly symmetrical n3v's Avatar
    Join Date
    Mar 2006

    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.

    #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
        int quantity;
        bool primestatus = true;
        cin >> quantity;
        int x = 2;
        while (primes.size() < quantity) {
        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; 
                     // 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) {
        cout << primes[quantity] << endl;
        return EXIT_SUCCESS;
    If you make a man a fire,
    he will be warm for a day.
    If you set a man on fire,
    he will be warm for the rest of his life.

  2. #2
    Registered User
    Join Date
    Jan 2005
    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 subscribe to a feed

Similar Threads

  1. Vectors
    By naseerhaider in forum C++ Programming
    Replies: 11
    Last Post: 05-09-2008, 08:21 AM
  2. How can i made vectors measuring program in DevC++
    By flame82 in forum C Programming
    Replies: 1
    Last Post: 05-07-2008, 02:05 PM
  3. How properly get data out of vectors of templates?
    By 6tr6tr in forum C++ Programming
    Replies: 4
    Last Post: 04-15-2008, 10:35 AM
  4. How to use Vector's in C++ !?!
    By IndioDoido in forum C++ Programming
    Replies: 3
    Last Post: 10-14-2007, 11:13 AM
  5. Points, vectors, matrices
    By subnet_rx in forum Game Programming
    Replies: 17
    Last Post: 01-11-2002, 02:29 PM