找出满足以下条件的最小素数:
a.3个连续素数的和
b.17个连续素数的和
c.45个连续素数的和
d.979个连续素数的和
e.本身为素数
- #include "stdafx.h"
- using namespace std;
- int main()
- {
- const unsigned int MaxNumber = 10000000;
- const unsigned int conditionNums[] = {3,17,45,979};
- clock_t pretime = clock();
- cout << "Start create prime table .../n";
- const unsigned MachineLength = sizeof(unsigned int) << 3;
- const unsigned int MaxSize = MaxNumber / (MachineLength<<1) + 1;
- unsigned int* Number = new unsigned int[MaxSize];
- memset(Number,0xFF,MaxSize*sizeof(unsigned int));
- for(unsigned int num = 3;num<MaxNumber;num+=2){
- if(Number[num/(MachineLength<<1)] & (0x1L<<((num>>1) % MachineLength))) {
- unsigned int NotPrime = num * num;
- if ((NotPrime / num != num))
- break;
- for(;NotPrime < MaxNumber ;NotPrime += num )
- if(NotPrime % 2)
- Number[NotPrime / (MachineLength<<1)] &= ~(0x1L << ((NotPrime>>1) % (MachineLength)));
- else
- continue;
- }
- }
- vector<unsigned int> PrimeNumber;
- PrimeNumber.push_back(2);
- for(unsigned int num = 3;num < MaxNumber;num +=2)
- if( Number[num /(MachineLength<<1)] & (0x1L<<(num>>1 % (MachineLength)))){
- PrimeNumber.push_back(num);
- }
- delete []Number;
- cout <<"Total "<<MaxNumber<<" Prime Number is "<<PrimeNumber.size()
- <<"/nStart analyze prime table .../n";
- unsigned long ConditionNumberSize = sizeof(conditionNums)/sizeof(unsigned int);
- vector<set<unsigned int>*> PrimeSet;
- vector<unsigned int> PrimeTotal;
- for(unsigned long i=0;i<ConditionNumberSize;i++)
- {
- PrimeSet.push_back(new set<unsigned int>);
- PrimeTotal.push_back(0);
- }
- for(unsigned int i = 0;i< PrimeNumber.size();i++)
- {
- for(unsigned int size=0;size < ConditionNumberSize;size++)
- {
- PrimeTotal[size] += PrimeNumber[i];
- if(i >= conditionNums[size]){
- PrimeTotal[size] -= PrimeNumber[i - conditionNums[size]];
- if(binary_search(PrimeNumber.begin(),PrimeNumber.end(),PrimeTotal[size]))
- PrimeSet[size]->insert(PrimeTotal[size]);
- }
- }
- }
- set<unsigned int> SolutionSet;
- for(unsigned int i = 0;i<PrimeSet.size()-1;i++)
- {
- SolutionSet.clear();
- set_intersection(PrimeSet[i]->begin(),PrimeSet[i]->end(),PrimeSet[i+1]->begin(),PrimeSet[i+1]->end(),inserter(SolutionSet,SolutionSet.begin()));
- PrimeSet[i]->clear();
- PrimeSet[i+1]->clear();
- PrimeSet[i+1]->operator =(SolutionSet);
- }
- copy(SolutionSet.begin(),SolutionSet.end(),ostream_iterator<unsigned int>(cout,"/t"));
- cout <<endl<<clock() - pretime <<"ms has used."<<endl;
- system("pause");
- return 0;
- }