我相信,这是非常有效的实施。通过合并 Primality 测试(O(1) 实现)可以进一步改进它。
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;
void printN(const vector<int> container, int count, ostream& out=cout, const string& delim=", ") {
for(int i=0; i<count; ++i)
out << container[i] << delim;
out << endl;
}
void printNPrimes(int count) {
static const int FIRST_PRIME = 2;
static vector<int> primes(1, FIRST_PRIME);
static int rangeEnd = 3;
if(primes.size() >= count) {
printN(primes, count);
return;
}
int remainingPrimeNumbers = count - primes.size();
while(remainingPrimeNumbers) {
bool is_prime = true;
for(int prime : primes) {
if(rangeEnd % prime == 0) {
is_prime = false;
break;
}
}
if(is_prime) {
primes.push_back(rangeEnd);
--remainingPrimeNumbers;
}
++rangeEnd;
}
printN(primes, count);
}
int main(int argc, const char *argv[])
{
if(argc < 2) {
cout << "usage: rund <count>";
return -1;
}
int count = atoi(argv[1]);
printNPrimes(count);
return 0;
}