int main() { int i, valueLength = 1, sumLength; long maxValue, maxSum; // Find the highest number we need to look up to while (1) { // Get the max possible value given a number of digits (i.e. all 9's) char maxValueStr[valueLength], *ptr; for (i = 0; i < valueLength; i++) maxValueStr[i] = '9'; maxValue = strtol(maxValueStr, &ptr, 10); // Get the sum of powers of this value (e.g. 999 -> sum = 9^5+9^5+9^5) // Find the length of the sum (how many digits make it up) char buffer[BUFFER_LEN]; maxSum = sumOfPowers(maxValue); sumLength = sprintf(buffer, "%ld", maxSum); // If sumLength < valueLength, then we only need to look at numbers with // less digits than valueLength, as we wouldn't be able to generate a // sum as large as a value for any greater number if (sumLength < valueLength) break; else valueLength++; } // Get the number of values we are looking up (or the value looking up to) // (e.g. valueLength = 6 -> 6 digits -> numValues = 100000) char numValues[valueLength], *ptr; numValues[0] = '1'; for (i = 1; i < valueLength; i++) numValues[i] = '0'; maxValue = strtol(numValues, &ptr, 10); // Sum all the numbers up to maxValue whose sum of powers is equal to the // number itself int sum = 0; for (i = 0; i < maxValue; i++) { if (sumOfPowers(i) == i) sum += i; } printf("%d\n", sum); }
int main() { long sumOfAll = 0; for (int i = 99; i < 999999; i++) { int digits[9]; int nDigits = fillDigits(i, digits); //printNumberAndDigits(i, nDigits, digits); //printNumberAndSumOfPowers(i, nDigits, digits, 2); double sop = sumOfPowers(nDigits, digits, 5); if (sop == i) { std::cout << i << "\n"; sumOfAll += i; } } std::cout << "sumOfAll: " << sumOfAll << "\n"; }