# Factorials of digits

Published on 2011-07-31Problem 34 is a slightly modified version of problem 30, so I solved the former with a slightly modified version of the code I used to solve the latter. It took *slightly* longer to run, as 9! is greater than 9^{5}, meaning that the central `for`

loop of my program ran to a higher ceiling (7 × 9! (~2.5 million) rather than 6 × 9^{5} (~350,000)).

Anyhoo, the text of problem 34 reads:

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.

The problem is asking you to find the sum of all factorions, of which there are only four. One of these (145!) is revealed in the problem text and two more (1! and 2!) are excluded from P.E.'s modified definition of the term. So your task is just to find the last factorion and add it to 145. The one thing to watch out for is that 0! is *1*, not 0: I had to modify my code from problem 30 very slightly to account for this.

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Problem034 { class Program { static void Main(string[] args) { int sumOfFactorialsOfDigits; int twoFactorial = 2; int threeFactorial = 3 * twoFactorial; int fourFactorial = 4 * threeFactorial; int fiveFactorial = 5 * fourFactorial; int sixFactorial = 6 * fiveFactorial; int sevenFactorial = 7 * sixFactorial; int eightFactorial = 8 * sevenFactorial; int nineFactorial = 9 * eightFactorial; int ceiling = 0; int ceilingDigits = 0; int total = 0; do { ceilingDigits++; ceiling += nineFactorial; } while (Math.Pow(10, ceilingDigits) < ceiling); for (int i = 3; i < ceiling; i++) { sumOfFactorialsOfDigits = 0; string number = i.ToString(); foreach (char c in number) { switch (c) { case '0': case '1': sumOfFactorialsOfDigits++; break; case '2': sumOfFactorialsOfDigits += twoFactorial; break; case '3': sumOfFactorialsOfDigits += threeFactorial; break; case '4': sumOfFactorialsOfDigits += fourFactorial; break; case '5': sumOfFactorialsOfDigits += fiveFactorial; break; case '6': sumOfFactorialsOfDigits += sixFactorial; break; case '7': sumOfFactorialsOfDigits += sevenFactorial; break; case '8': sumOfFactorialsOfDigits += eightFactorial; break; case '9': sumOfFactorialsOfDigits += nineFactorial; break; } if (sumOfFactorialsOfDigits > i) break; } if (sumOfFactorialsOfDigits == i) { total += i; } } Console.WriteLine(total); } } }