Sunday 12 April 2009

PROJECT EULER #34

Link to 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.


using System;

namespace project_euler
{
class Program
{
static void Main()
{
//Problem 34
DateTime start = DateTime.Now;
long total = 0;
for (int i = 3; i < 50000; i++)
{
long sum = 0;
string s = i.ToString();
for (int j = 0; j < s.Length; j++)
sum += Factorial(int.Parse(s[j].ToString()));
if (sum == i)
total += sum;
}
Console.WriteLine(total);
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
public static int Factorial(int n)
{
int number = n;
if (n == 0) return 1;
for (int i = 1; i < n; i++)
number *= i;
return number;
}
}
}

No comments: