Square digit chains | Project Euler | Problem #92

URL to the problem page: https://projecteuler.net/problem=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;

int finddigits(int a) {
    int cnt = 1;
    while (a >= 10) {
        a /= 10;
        cnt++;
    }
    return cnt;
}

int power(int aint b) {
    int result = 1;
    for (int i = 0; i < b; i++) {
        result *= a;
    }
    return result;
}

int main()
{
    int i, j, number, cnt = 0, digitnumber, digits[8] = { 0 };

    for (i = 1; i < 10000000; i++) {
        number = i;
        while (number != 1) {
            digitnumber = finddigits(number);
            for (j = digitnumber; j > 0; j--) {
                digits[j - 1] = (number % power(10, j)) / (power(10, (j - 1)));
            }
            number = 0;
            for (j = 0; j < digitnumber; j++) {
                number += (power(digits[j], 2));
            }
            if (number == 89) {
                cnt++;
                break;
            }
        }
    }
    cout << "Number of starting numbers that will arrive at 89 below 10.000.000 is  =  " << cnt << endl;
    return 0;
}



Comments

My photo
Ercan Tomac
instagram.com/ercantomac