#include <iostream>
#include <vector>
#include <cmath>
usingnamespace std;
bool Prime(int a)
{ for(int c = 2; c<=sqrt((double)a); c++) // use sqrt(a), not a/2
{ if (a%c == 0)
returnfalse;
}
returntrue;
}
int main ()
{ int c;
unsigned b;
vector<int>prime3;
cout << "Enter number of desired prime numbers: ";
cin >> b;
while (b<4) // This should be a loop, not an if statement
{ cout<< "Error: Enter a number more than 3. \nEnter a positive integer: ";
cin >> b;
}
c = 3; // First prime
while (prime3.size() < b)
{ if (Prime(c))
{ cout << c << " is prime\n";
prime3.push_back (c); // Add to vector
}
else
cout << c << " is not prime \n";
c++;
}
cout << "The first " << b << " primes are: " << endl;
for (unsigned i=0; i<prime3.size(); i++)
cout << prime3[i] << " ";
cout << endl;
system ("pause");
return 0;
}
Sometimes it helps if you write your plan down in plain English like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
Read number of primes from the user.
Create a vector to hold the primes.
set number to 3 - first prime
while size of vector is smaller than the number of primes
if number is a prime
add it to the vector
increment number by 2 // skip even numbers
end while
Finally print all the numbers in the vector