I'm having trouble improving the performance of the solution to the Project Euler 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.
I've done the following :
private static readonly int max = (int)Factorial(9)*7;
private static void Main()
{
long sum = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 3; i <= max; i++)
{
if (IsCuriousNumber(i))
{
sum += i;
}
}
sw.Stop();
Console.WriteLine(sum);
Console.WriteLine("Time to calculate in milliseconds : {0}", sw.ElapsedMilliseconds);
Console.ReadKey();
}
private static long Factorial(int input)
{
int sum = 1;
for (int i = 1; i <= input; i++)
{
sum *= i;
}
return sum;
}
private static bool IsCuriousNumber(long input)
{
char[] digits = input.ToString().ToCharArray();
long sum = digits.Sum(t => Factorial((int) char.GetNumericValue(t)));
return sum == input;
}
It's pretty much self-explanatory .. We have a method to find the factorial of specific number and one more method that checks if a number is "curious" as described in the problem above. We do this by simply converting the input to a char
array than we have a variable that just sum's up all the factorials of the digits in the number.