Time Limit: 1000MS | Memory Limit: 65536K |
Description
Input
Output
Sample Input
2
3
17
41
20
666
12
53
0
Sample Output
1
1
2
3
0
0
1
2
老版本(数组版本)
#include <iostream> #include <vector> #include <algorithm> using namespace std; void MakePrimeNumber(vector<int>& PrimeNumbers, int Max) { PrimeNumbers.clear(); PrimeNumbers.push_back(2); for (int i = 3; i < Max; i = i + 2) { bool IsPrimer = true; if ( 0 == (i % 2)) { IsPrimer = false; } for (int j = 3; j < i; j = j + 2) { if (i % j == 0) { IsPrimer = false; break; } } if (IsPrimer) { PrimeNumbers.push_back(i); } } } void MakeSum(const vector<int>& PrimeNumbers, int* SumArray) { int Size = PrimeNumbers.size(); for (int Index = 0; Index < Size; Index++) { for (int IndexJ = 0; IndexJ < Size; IndexJ++) { if (Index < IndexJ) { SumArray[Index * Size +IndexJ] = SumArray[Index * Size +IndexJ - 1] + PrimeNumbers[IndexJ]; } if (Index > IndexJ) { SumArray[Index * Size + IndexJ] = -1; } if (Index == IndexJ) { SumArray[Index * Size + IndexJ] = PrimeNumbers[Index]; } } } } int main() { int Max = 10000; vector<int> PrimerNumbers; MakePrimeNumber(PrimerNumbers, Max); int Size = PrimerNumbers.size(); int* SumArray = new int[Size * Size]; MakeSum(PrimerNumbers, SumArray); int i = 0; int Result = 0; while(true) { cin >> i; if (i == 0) { break; } Result = count(SumArray, SumArray + Size * Size, i); cout << Result << endl; } delete[] SumArray; return 0; }
新版本
#include <iostream> #include <vector> #include <algorithm> using namespace std; void MakePrimeNumber(vector<int>& PrimeNumbers, int Max) { PrimeNumbers.clear(); PrimeNumbers.push_back(2); for (int i = 3; i < Max; i = i + 2) { bool IsPrimer = true; if ( 0 == (i % 2)) { IsPrimer = false; } for (int j = 3; j < i; j = j + 2) { if (i % j == 0) { IsPrimer = false; break; } } if (IsPrimer) { PrimeNumbers.push_back(i); } } } void MakeSum(const vector<int>& PrimeNumbers, vector<int>& SumVec, int Max) { SumVec.clear(); int Size = PrimeNumbers.size(); int PreValue = 0; for (int Index = 0; Index < Size; Index++) { for (int IndexJ = Index; IndexJ < Size; IndexJ++) { if (Index == IndexJ) { PreValue = PrimeNumbers[Index]; SumVec.push_back(PreValue); } else { PreValue = PreValue + PrimeNumbers[IndexJ]; if (PreValue > Max) { break; } SumVec.push_back(PreValue); } } } } int main() { int Max = 10000; vector<int> PrimerNumbers; MakePrimeNumber(PrimerNumbers, Max); vector<int> SumVec; MakeSum(PrimerNumbers, SumVec, Max); int i = 0; int Result = 0; while(true) { cin >> i; if (i == 0) { break; } Result = count(SumVec.begin(), SumVec.end(), i); cout << Result << endl; } return 0; }