Project Euler task 46

It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.

9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12

It turns out that the conjecture was false.

What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?

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

#include < iostream >
#include < math.h >

using namespace std;

const int ciMax = 1000000;
const int ciSeqCount = 4;

int iEratArray[ciMax];

bool isRepresentable(int _n) {
if (_n % 2 == 0)
return false;

if (iEratArray[_n] == 0)
return false;

for (int i = 3; i < _n; i += 2) {
if (iEratArray[i]) // select a prime
continue;

int iX = (_n - i) / 2;
double dSqrt = sqrt((double) iX);
if (dSqrt - floor(dSqrt) > 0)
continue;

return true;
}

return false;
}

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

// eratosphene's sieve
iEratArray[0] = 1;
iEratArray[1] = 1;
for (int k = 2; k < ciMax; k++) {
if (iEratArray[k]) // if not prime, continue
continue;

for (int j = 2; k * j < ciMax; j++)
iEratArray[k * j] = 1; // mark as not prime
}

for (int i = 3; i < ciMax; i += 2) {
if (!isRepresentable(i) && iEratArray[i]) {
cout << i << endl;
break;
}
}

return 0;
}

Comments

Popular Posts