Thursday, April 10, 2014

Project Euler Solution using C#: Problem 9: Special Pythagorean Triplet

Problem:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
My Solution:

static void Main(string[] args)
{
    int total = 1000;
    for (int i = 1; i <= total; i++)
    {
        for (int j = 1; j <= total; j++)
        {
            int k = total - i - j;
            int res = (i * i) + (j * j) + (k * k);
            int r = i + j + k;

            int left = (i * i) + (j * j);
            int right = (k * k);

            if (left == right && i < j && j < k)
            {
                Console.WriteLine(i + " " + j + " " + k);
                Console.WriteLine(Math.Pow(i, 2) + " " + Math.Pow(j, 2) + " " + Math.Pow(k, 2));
                Console.WriteLine(i * j * k);
                Console.WriteLine("---------------------");
            }
        }
    }
    Console.ReadLine();
}

Note: You can simplifies the coding :)

No comments:

Post a Comment