#include <stdio.h> #include <stdlib.h> //Returns a^b int power ( int a , int b ); //Returns a! int factorial ( int a ); //We are searching for all factorions - numbers who are equal to the sum of the factorials of their digits int main () { //Candidate factorion i, candidate number of digits for it j, and index k int i , j , k ; //Our upper bound number of digits int d = 2 ; //The sum of the factorial of the digits of i int sumoffactofdigits ; //Sum of all the factorions int answer = 0 ; //The minimum value for a number d digits long is 10^d //The maximum sum of the factorial of the digits for a number d digits long is 9!d //Thus 10^d must be <= 9!d for us to consider searching; we'll find the d that is too many digits long while ( 1 ) { if ( power ( 10 , d - 1 ) > ( factorial ( 9 ) * d )) { goto done ; } d ++ ; } done: ; //Search for factorions - exclude single digits for ( i = 10 ; i < power ( 10 , d ); i ++ ) { //Let j represent how many digits long i is for ( j = d - 1 ; j >= 2 ; j -- ) { if (( i - i % power ( 10 , j - 1 )) != 0 ) { goto keepgoing ; } } keepgoing: ; //So we have j digits...let's get the sum of the factorials of the digits sumoffactofdigits = 0 ; for ( k = 1 ; k <= j ; k ++ ) { sumoffactofdigits += factorial (( i % power ( 10 , k ) - i % power ( 10 , k - 1 )) / ( power ( 10 , k - 1 ))); } if ( i == sumoffactofdigits ) { printf ( "%d

" , i ); answer += i ; } } printf ( "The answer is %d

" , answer ); return 0 ; } //Returns a^b int power ( int a , int b ) { int answer = 1 ; int i ; for ( i = 0 ; i < b ; i ++ ) { answer *= a ; } return answer ; } //Returns a! int factorial ( int a ) { if ( a < 1 ) { return 1 ; } else { return a * factorial ( a - 1 ); } }