Ok, I'm a newbie. I've been reading through the www.cplusplus.com tutorials and now I've turned to doing simple exercises that I've found in free online resources and also ones that I've devised for myself. One of my first programs was a program that discovered prime numbers using nested [inline code]for[/inline code] loops. But now that I've been reading about vectors, I think I see a better way to do it. I've set myself the task of developing a faster program to factor numbers and discover primes. Here is the program with comments. Conceptually, I think it looks sound. It compiles. But it keeps giving me runtime errors. I've stuck in a bunch of printouts so that I can see where it fails. It doesn't even print one prime number before failing. I don't really know how to debug yet, this is the first program I've had that will compile but not run. I guess I need to learn debugging. But if anyone can take a quick peak and tell me what's wrong, I'd just feel more satisfied and able to move on to the next lesson :).
EDIT: Well, I got it to run. I guess had intialized iter before I put anything into the vector, so when I used *iter it was pointing to a null value. But now the code just does an infinite loop. This is something I think I can fix, but I'll just leave this up here anyway. I updated with the latest code.
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
cout<<"Now displaying the first 20 prime numbers\n ";
vector <int> factors;
vector <int>::iterator iter;
factors.push_back(1);
iter=factors.begin();
int num=0, a=1;
while (factors.size()<20){ //while there are <20 primes in the vector
num =(factors.back()+(2*a));/*the num is the last prime we've found
+ 2*the number of wrong numbers we've found since the last prime*/
cout<<factors.size();
if (*iter == factors.back()){ /*if the current prime is the last one in the list,
that means the current num is a prime, add it to the list, then print it */
factors.push_back(num);
cout << factors.back() << ", ";
iter=factors.begin(); //start the while loop with a fresh iterator
a=1; //start cycling nums again, starting at 2+the current prime in the list (should be the new prime we just pushed back)
}
else if (!(num % *iter) ) { //if the num under consideration divides into the current prime in the list with no remainder, start on the next num
iter=factors.begin(); //reset to the first prime in the list
a++;//so the program knows we found a wrong number and to try the next odd number
}
else
iter++; //if neither of these two conditions are met, repeat the while loop with the next prime in the list
}
cout << "\n. Finished! Found " << factors.size() <<" factors";
cin.get();
return 0;
}