题:给N,输出前N个素数
素数:除了2都是偶数。
验证N是素数:2-N的开方与N最大公约数是1。
假设已知前K个素数,第K+1个素数与已知素数求最大公约数。
上代码——C++好久不写,弄了我好久:
头文件:
#ifndef PRIME_HOLDER_H
#define PRIME_HOLDER_H
#include <vector>
using std::vector;
class PrimeHolder{
public:
void print_prime(int N);
PrimeHolder();
void reset(void);
virtual ~PrimeHolder();
private:
vector<int> primeList;
int gcd(int x, int y);
void printN(int num);
};
#endif
定义:
#include <iostream>
#include <cmath>
#include "printprime.h"
using namespace std;
PrimeHolder::PrimeHolder(){
primeList.push_back(2);
primeList.push_back(3);
primeList.push_back(5);
primeList.push_back(7);
primeList.push_back(11);
primeList.push_back(13);
primeList.push_back(17);
primeList.push_back(19);
}
PrimeHolder::~PrimeHolder(){
}
void PrimeHolder::reset(void){
primeList.clear();
primeList.push_back(2);
primeList.push_back(3);
primeList.push_back(5);
primeList.push_back(7);
primeList.push_back(11);
primeList.push_back(13);
primeList.push_back(17);
primeList.push_back(19);
}
int PrimeHolder::gcd(int x, int y){
if (y==0) return x;
else return gcd(y, x%y);
}
void PrimeHolder::printN(int num){
int i = 0;
for(vector<int>::iterator iter = primeList.begin(); i < num; ++iter, ++i)
cout << *iter << " ";
cout << endl;
}
void PrimeHolder::print_prime(int N){
if (N < primeList.size())
printN(N);
else {
int start = primeList.back() + 1;
while (primeList.size() < N){
bool tag = true;
int max = sqrt((double)start);
for (vector<int>::iterator iter = primeList.begin(); *iter<max; iter++){
if (gcd(start, *iter)!=1) {
tag = false;
break;
}
}
if (tag) {
primeList.push_back(start);
start++;
}
else
start++;
}
printN(N);
}
}
#include <ctime>
#include <iostream>
#include <vector>
#include "primeholder.h"
using namespace std;
int main(){
PrimeHolder ph;
clock_t start, finish;
vector<double> times;
start = clock();
ph.print_prime(100);
finish = clock();
times.push_back((double)(finish-start)/CLOCKS_PER_SEC);
ph.reset();
start = clock();
ph.print_prime(1000);
finish = clock();
times.push_back((double)(finish-start)/CLOCKS_PER_SEC);
ph.reset();
start = clock();
ph.print_prime(10000);
finish = clock();
times.push_back((double)(finish-start)/CLOCKS_PER_SEC);
ph.reset();
start = clock();
ph.print_prime(100000);
finish = clock();
times.push_back((double)(finish-start)/CLOCKS_PER_SEC);
// no reset
start = clock();
ph.print_prime(1000000);
finish = clock();
times.push_back((double)(finish-start)/CLOCKS_PER_SEC);
for(vector<double>::iterator iter = times.begin(); iter != times.end(); iter++)
cout << *iter << " " ;
cout << endl;
}
唔,N=100000时要超过1s,1000000时要几分钟,求各位巨巨指点。