Problem #34 hard
Digit Factorials
is a curious number, as .
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Implementations
// Answer: 40730
// Authored by: Tim Varley π// Assisted-by: Grok Code Fast via Crush π <crush@charm.land>
#include <iostream>#include <vector>#include <string>
long long digit_factorials() { std::vector<long long> fact(10,1); for(int i=2; i<10; i++) fact[i] = fact[i-1] * i; long long sum = 0; for(long long i=10; i<10000000; i++) { std::string s = std::to_string(i); long long sf = 0; for(char c : s) sf += fact[c-'0']; if(sf == i) sum += i; } return sum;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]) { std::cout << digit_factorials() << std::endl;}#endif // UNITTEST_MODESolution Notes
Mathematical Background
A number is βcuriousβ if it equals the sum of the factorials of its digits. For example, 145 = 1! + 4! + 5!.
Factorials grow rapidly: 9! = 362,880. The maximum sum for an n-digit number is n Γ 9!, so we can find an upper bound where the maximum digit sum becomes smaller than n-digit numbers.
Algorithm Analysis
The implementations use brute force with optimization:
- Precompute factorials for digits 0-9
- Iterate from 10 to an upper bound (7 Γ 9! = 2,540,160)
- For each number, sum the factorials of its digits
- If the sum equals the number, add it to the total
The upper bound comes from the fact that 8 Γ 9! has 7 digits while the sum has 7 digits, but 8-digit numbers would exceed the maximum possible sum.
Performance Analysis
- Time Complexity: O(U Γ D) where U is the upper limit (~2.5 million) and D is maximum digits (7), resulting in ~17 million operations. Executes in milliseconds on modern hardware.
- Space Complexity: O(1) - only factorial array of size 10.
- Execution Time: Fast (under 1 second), suitable for interactive applications.
- Scalability: Linear in the upper bound, which is determined by mathematical limits.
Key Insights
- Only two numbers satisfy the condition: 145 and 40,585
- The upper bound calculation prevents unnecessary computation
- Single-digit numbers (1, 2) are excluded as they are trivial cases
- Factorial digit sums create a natural upper limit due to rapid growth
Educational Value
This problem teaches:
- Factorial computation and properties
- Digit manipulation and string processing
- Mathematical bounds and optimization in brute-force algorithms
- The importance of excluding trivial cases
- How mathematical analysis can reduce computational complexity