Among the problems in the posted code.
- The inner loop body will never be entered because
primes
is initially empty the only code that changes it is in that loop.
- Even after fixing the initial primes content with
{2}
and starting the counter loop with 3
, the logic in the inner loop is still wrong. It appends on ever non-zero modulo. That shouldn't be done at all in the inner loop. Rather, the loop should break on any zero-modulo, and the outer loop then only appends to primes
when it knows the inner loop didn't break early.
- The final reporting loop assumes there are 100 primes in the first 100 numbers, which clearly isn't the case. Either it should be iterating based on container size, using iterators, or better still, just used ranged-for.
- Minor: the
current_number
is pointless; just use i
from the outer loop and start it at 3
.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> primes = {2};
for (int i = 3; i <= 100; i++)
{
bool isprime = true;
for (auto x : primes)
{
if (i % x == 0)
{
isprime = false;
break;
}
}
if (isprime)
primes.emplace_back(i);
}
for (auto x : primes)
std::cout << x << ' ';
std::cout << '
';
}
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Note
There are better ways to do this. I suggest you investigate how to build a Sieve of Eratosthenes or similar sieve. In truth, the above code is already over halfway there. It wouldn't take much more to do it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…