C#: Project Euler Solutions to Problems 29, 30, and 34

http://projecteuler.net

Problem 29

How many distinct terms are in the sequence generated by a^b for 2 (le) a (le) 100 and 2 (le) b (le) 100?

LinkedList<double> distinct_values = new LinkedList<double>();
for (int i = 2; i <= 100; i++)
{
    for ( int j = 2 ; j <= 100; j ++)
    {
        double temp = Math.Pow(i, j);
        if (!distinct_values.Contains(temp))
        {
            distinct_values.AddLast(temp);
            Console.WriteLine(temp);
        }
    }
}
Console.WriteLine("Total : " + distinct_values.Count );

Problem 30

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

double super_sum = 0;
for (int j = 2; j &lt; 1000000; j++)
{
    int num = j;
    double sum_of_dig = 0;
    string num_string = num.ToString();
    for (int i = 0; i &lt; num_string.Length; i++)
    {
        double pow = int.Parse(num_string[i].ToString());
        sum_of_dig += Math.Pow(pow, 5);
    }
    if (sum_of_dig == num)
        super_sum += sum_of_dig;
}
Console.WriteLine("Final Sum :"+ super_sum);

Problem 34

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.

static void Main(string[] args)
{
    long bigsum = 0;
    for (int q = 3; q < 1000000; q++)
    {
        long num = q;
        string num_String = num.ToString();
        long sum = 0;
        for (int j = 0; j < num_String.Length; j++)
        {
            int temp = int.Parse(num_String[j].ToString());
            sum += Factorial(temp);
        }
        if (num == sum)
            bigsum += num;
    }
    Console.WriteLine("Answer : " +bigsum);
}
 
public static long Factorial(long x)
{
    long fact = 1;
    long i = 1;
    while (i <= x)
    {
        fact = fact * i;
        i++;
    }
    return fact;
}

Leave a Reply

Your email address will not be published.