采用vs2010编译。
//findPrimeNumber.h
#pragma once
#include <iostream>
#include <vector>
using namespace std;
// use the Sieve of Eratosthenes method to find the prime numbers in range from 1 to n
vector<unsigned int> findPrimeNumber(unsigned int n)
{
vector<bool> boolVector(n,true);
vector<unsigned int> resultVector;// save the prime numbers.
for(unsigned int i = 2; i*i <n; ++i)
if(boolVector[i] == true){
for(unsigned int j = i; i*j < n; ++j){
boolVector[i*j] = false;
}
}
for(unsigned int i = 2; i< n; ++i){
if(boolVector[i])
resultVector.push_back(i);
}
if(resultVector.size()==0){
cout << "There is " << resultVector.size() << " prime numbers.\n";
}
else{
cout << "There is " << resultVector.size() << " prime numbers.They are:\n";
for(unsigned int i = 0; i < resultVector.size(); ++i)
cout << resultVector[i] << endl;
}
return resultVector;
}
findPromeNumber 函数使用事例如下:
// sieveofEratosthenesExample.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "findPrimeNumber.h"
int _tmain(int argc, _TCHAR* argv[])
{
cout << "This is a example to display that\n"
<< "how to use the findPrimeNumber function to find prime numbers.\n";
cout << "----------------------------------------------------------------\n";
unsigned int upperLimitValue = 0;
cout << "Please input the upper limit value: ";
cin >> upperLimitValue;
findPrimeNumber(upperLimitValue);
return 0;
}
其中 stdafx.h为建立控制台应用程序时,系统自动生成。
计算结果如下所示: