C#: Project Euler Solutions to Problems 9, 13, and 38

For solving ten consecutive problems (1-10).

http://projecteuler.net/problem=9

a2 + b2 = c2

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

for (int a = 1; a < 1000; a++)
{
    for (int b = 1; b < 1000; b++)
    {
        double a_pow2 = Math.Pow(a, 2);
        double b_pow2 = Math.Pow(b, 2);
        double c_root = Math.Sqrt(a_pow2 + b_pow2);
        if ((a + b + c_root) == 1000.00)
        {
            Console.WriteLine("a "+a+" b "+b+" c "+c_root+" product : "+(a * b * c_root));
            break;
        }
    }
}

http://projecteuler.net/problem=13

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

string[] linerows = totalstring.Split('\n');
long sum = 0;
foreach (string row in linerows)
{
    // Console.WriteLine(row);
    string longnum = row;
    string num11 = longnum.Substring(0, 11);
    long num = long.Parse(num11);
    sum += num;
}
Console.WriteLine(sum.ToString().Substring(0, 10));

http://projecteuler.net/problem=38

What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, … , n) where n 1?

static void Main(string[] args)
{
    int number = 0;
    int numberofappend = 2;
    int max = 0;
    while (true)
    {
        number++;
        string catstring = appendmore(number, numberofappend);
        if (catstring.Length > 9)
        {
            number = 0;
            numberofappend++;
        }
        else if  (catstring.Length == 9 && Order(catstring))
        {
            int catint = int.Parse(catstring);
            if (max < catint)
            {
                max = catint;
                Console.WriteLine("max so far : "+ max);
            }
        }
    }
}
public static string appendmore(int num, int howmany)
{
    string cat = "";
    for (int i = 1; i <= howmany; i++)
        cat += "" + num * i;
    return cat;
}
public static bool Order(string n)
{
    string mynum = "" + n;
    int[] int_array = new int[mynum.Length];
    for (int i = 0; i < mynum.Length; i++)
    {
        int_array[i] = int.Parse(mynum[i].ToString());
    }
    Array.Sort(int_array);
    if (int_array[0] == 1)
    {
        int count = 2;
        for (int j = 1; j < int_array.Length; j++)
        {
            if (count == int_array[j])
                count++;
            else
                return false;
        }
    }
    else
        return false;
    return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *