Project Euler task 92

A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.

For example,

44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89

Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.

How many starting numbers below ten million will arrive at 89?

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

#include < iostream >

using namespace std;

const unsigned int nMaxNum = 10000000;

unsigned int pArray[nMaxNum];

unsigned int getSqrSum(unsigned int _n) {
unsigned int nRes = 0;
while (_n) {
unsigned int nTemp = (_n % 10);
nRes += nTemp * nTemp;
_n /= 10;
}

return nRes;
}

int main() {
memset(pArray, 0, nMaxNum);

unsigned int nSum = 0;
for (int i = 1; i < nMaxNum; i++) {
unsigned int nTemp = i;
while (nTemp != 1 && nTemp != 89) {
nTemp = getSqrSum(nTemp);

if (pArray[nTemp])
nTemp = pArray[nTemp];
}

nSum += (nTemp == 89) ? 1 : 0;

pArray[i] = nTemp;
}

cout << nSum << endl;

return 0;
}

Comments

Popular Posts