Project Euler task 50

The prime 41, can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13

This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes?

----------------------------------------------------------------

#include < iostream >

using namespace std;

const int ciMax = 1000000;

int iEratArray[ciMax];


int main() {
memset(iEratArray, 0, ciMax);

iEratArray[0] = 1;
iEratArray[1] = 1;
for (int i = 2; i < ciMax; i++) {
if (iEratArray[i]) // if not prime, continue
continue;
for (int j = 2; i * j < ciMax; j++)
iEratArray[i * j] = 1; // mark as not prime
}


int iSum = 0;
int iMaxSum = 0;
int iTerms = 0;
int iMaxTerms = 0;
for (int k = 2; k < ciMax; k++) {
if (iEratArray[k])
continue;
iSum = 0;
iTerms = 0;
for (int i = k; i < ciMax && iSum < ciMax; i++) {
if (!iEratArray[i]) {
iSum += i;
iTerms++;
if ((iSum < ciMax) && !iEratArray[iSum] && (iSum > iMaxSum) && (iTerms > iMaxTerms)) {
iMaxSum = iSum;
iMaxTerms = iTerms;
}
}
}
}

cout << iMaxSum << endl;

return 0;
}

Comments

Popular Posts