Friday 10 April 2009

PROJECT EULER #9

Link to Project Euler problem 9

A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc.


Brute-force with three for loops.
using System;

namespace ProjectEuler
{
class Program
{
static void Main(string[] args)
{
//Problem 9
DateTime start = DateTime.Now;
for (int a = 1; a < 1000; a++)
{
for (int b = a + 1; b < 1000-a; b++)
{
for (int c = b + 1; c < 1000-b; c++)
if (a + b + c == 1000 && (Math.Pow(a, 2)) + Math.Pow(b, 2) == Math.Pow(c, 2))
{
TimeSpan time = DateTime.Now-start;
Console.WriteLine("a = {0}, b = {1}, c = {2}, the product is {3}\nThis took {4}", a, b, c, a * b * c, time);
}
}
}
Console.ReadKey();
}
}
}

No comments: