Digit factorials | Project Euler | Problem #34
URL to the problem page: https://projecteuler.net/problem=34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
#include <iostream>
using namespace std;
long long int power(long long int a, long 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, digitnumber, sum, factorial, j, k;
for (i = 3; i < 1000000; i++) {
digitnumber = finddigits(i), sum = 0;
long long int* digits = new long long int[digitnumber];
for (j = digitnumber; j > 0; j--) {
factorial = 1;
digits[j - 1] = (i % power(10, j)) / (power(10, (j - 1)));
for (k = 2; k <= digits[j - 1]; k++) {
factorial *= k;
}
sum += factorial;
}
if (sum == i) {
result += i;
}
}
cout << "Sum of all numbers which are equal to the sum of the factorial of their digits is = " << result << endl;
return 0;
Comments
Post a Comment