#include <vector>
#include <iostream>
usingnamespace std;
vector<int>prime;
bool is_prime(int n)
{
for (int p = 0; p<prime.size(); ++p)
if (n%prime[p]==0) returnfalse; // no remainder: prime[p] divided
returntrue; // no smaller prime could divide
}
int main()
{
cout << " Enter a max value "; '\n'for (int max; cin>>max;)
prime.push_back(max);
for (int i=0; i<=prime.size(); ++i)
if (is_prime(max)) prime.push_back(max); // add new prime to vector
cout << "Primes: ";
for (int p = 0; p<prime.size(); ++p)
cout << prime[p] << '\n';
}
#include <vector>
#include <iostream>
usingnamespace std;
vector<int> prime;
bool is_prime(int n) {
for (unsignedint p = 0; p < prime.size(); ++p) {
if (n % prime[p] == 0)
returnfalse; // no remainder: prime[p] divided
}
returntrue; // no smaller prime could divide
}
int main() {
int max;
cout << " Enter a max value ";
cin >> max;
for (int i = 2; i <= max; ++i) {
if (is_prime(i))
prime.push_back(i); // add new prime to vector
}
cout << "Primes: ";
for (unsignedint p = 0; p < prime.size(); ++p)
cout << prime[p] << '\n';
}
Line 20 is defective. The ; terminates the statement. the '\n' by itself does nothing and you missing both a << operator and a ; at the end.
line 23-24: Why are you looping here? You're getting multiple values of max and pushing them onto the vector without determining whether they are prime or not.
Line 25-26: If I enter one value, prime.size() is 1 and the loop will execute once.
Line 26: max is out of scope. max is only defined for the duration of the for loop at lines 23-24.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{ int max;
cout << " Enter a max value " << '\n';
cin>>max;
for (int i=2; i<=max; ++i)
if (is_prime(i))
prime.push_back(i); // add new prime to vector
cout << "Primes: ";
for (int p = 0; p<prime.size(); ++p)
cout << prime[p] << '\n';
system ("pause");
}
There is not a "magic number"... Do some exercises until you feel you have learnt something and then move on. Probably you will have to re-look at many things but this is natural...