#include <iostream>
#include <vector>
class Primes
{
std::vector<int> primes;
int n, sqrt_n;
bool testPrime() const
{
for(int i=0; i<primes.size() && primes[i]<=sqrt_n; ++i)
if(n%primes[i]==0) return false;
return true;
}
public:
Primes() : n(2), sqrt_n(1) { }
int operator()()
{
if(n==2) { n=3; return 2; } // The only even prime number
for(;;n+=2)
{
while(sqrt_n*sqrt_n<n) ++sqrt_n; // Maintain the square root
if(testPrime())
{
primes.push_back(n); // Add it to the list of primes
n+=2;
return n-2;
}
}
}
int operator[](unsigned n)
{
if(!n) return 2;
while(primes.size()<n) operator()();
return primes[n-1];
}
};
int main(int argc, char**argv)
{
Primes primes;
int n = argc==2 ? atoi(argv[1]) : 1000;
// Print the first n numbers in the stream
for(int i=0; i<n; ++i)
std::cout << primes[i] << " ";
return 0;
}