I am making a C++ program to find prime numbers using the Sieve of Eratosthenes
Currently I have the following code:
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class is_multiple_of {
int m_div;
public:
is_multiple_of(int div) : m_div(div) {}
bool operator()(int n) { return ((n > m_div) && (0 == n % m_div)); }
};
int main ()
{
vector<int> v;
for (int i=2; i<=100; i++) v.push_back(i);
v.erase( remove_if(v.begin(), v.end(), is_multiple_of(2)), v.end() );
v.erase( remove_if(v.begin(), v.end(), is_multiple_of(3)), v.end() );
v.erase( remove_if(v.begin(), v.end(), is_multiple_of(5)), v.end() );
v.erase( remove_if(v.begin(), v.end(), is_multiple_of(7)), v.end() );
for (unsigned i=0; i<v.size(); ++i)
cout << v[i] << " ";
cout << endl << v.size();
return 0;
}
which works fine i.e. it says there are 25 primes between 1 and 100 (which is correct). However, if i want to know the first 500 primes for example, it will say there are 118 where in reality there are 95. To correct this issue, I have to add more multiples to remove i.e. v.erase( remove_if(v.begin(), v.end(), is_multiple_of(11)), v.end() );
and then add more is_multiple_of()
's.
Is there a way to make this more efficient rather than just having it remove more multiples of previously found primes?
sqrt(n)
. Forn==100
this is 10 but forn==500
this is 19. – uesp