Created
December 1, 2016 06:50
-
-
Save vczh/b74414a76d932a66ebb5780f8b042afb to your computer and use it in GitHub Desktop.
The Prime 41 (2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <type_traits> | |
using namespace std; | |
const int Max = 1000; | |
bool isPrime[Max]; | |
int primes[Max] = { 0 }; | |
int primeCount = 0; | |
int minIndex = 0; | |
int maxIndex = 0; | |
int maxSum = 2; | |
void FillPrimes() | |
{ | |
isPrime[0] = false; | |
isPrime[1] = false; | |
for (int i = 2; i < Max; i++) | |
{ | |
isPrime[i] = true; | |
} | |
for (int i = 2; i < Max; i++) | |
{ | |
if (isPrime[i]) | |
{ | |
for (int j = i * 2; j < Max; j += i) | |
{ | |
isPrime[j] = false; | |
} | |
} | |
} | |
for (int i = 2; i < Max; i++) | |
{ | |
if (isPrime[i]) | |
{ | |
primes[primeCount++] = i; | |
} | |
} | |
} | |
void PrintResult() | |
{ | |
for (int i = minIndex; i < maxIndex; i++) | |
{ | |
cout << primes[i] << " + "; | |
} | |
cout << primes[maxIndex] << " = " << maxSum << endl; | |
} | |
int main() | |
{ | |
FillPrimes(); | |
int start = 0; | |
int sum = 2; | |
for (int i = 1; i < primeCount; i++) | |
{ | |
int newSum = sum + primes[i]; | |
if (newSum >= Max) | |
{ | |
i--; | |
sum -= primes[start++]; | |
} | |
else | |
{ | |
sum = newSum; | |
} | |
if (isPrime[sum]) | |
{ | |
int d1 = i - start; | |
int d2 = maxIndex - minIndex; | |
if ((d1 > d2) || (d1 == d2 && sum > maxSum)) | |
{ | |
maxSum = sum; | |
minIndex = start; | |
maxIndex = i; | |
PrintResult(); | |
} | |
} | |
} | |
PrintResult(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment