Digit fifth powers | Project Euler | Problem #30

URL to the problem page: https://projecteuler.net/problem=30

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴
8208 = 8⁴ + 2⁴ + 0⁴ + 8⁴
9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴

As 1 = 1⁴ is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.



#include <iostream>
using namespace std;

long long int power(long long int along long int b) {
    long long int result = 1;
    for (int i = 0; i < b; i++) {
        result = result * a;
    }
    return result;
}
long long int finddigits(long long int a) {
    long long int counter = 1;
    while (a >= 10) {
        a /= 10;
        counter++;
    }
    return counter;
}

int main()
{
    long long int i, result = 0;
    for (i = 2; i < 10000000; i++) {
        long long int digitnumber = finddigits(i), sum = 0, j;
        long long int* digits = new long long int[digitnumber];
        for (j = digitnumber; j > 0; j--) {
            digits[j - 1] = (i % power(10, j)) / (power(10, (j - 1)));
        }
        for (j = 0; j < digitnumber; j++) {
            sum += power(digits[j], 5);
        }
        if (sum == i) {
            result += i;
        }
    }
    cout << endl << "Sum of all the numbers that can be written as the sum of fifth powers of their digits is  =  " << result << endl;

Comments

My photo
Ercan Tomac
instagram.com/ercantomac