Yes, I know I skipped problem 8, but it involves strings, and I found nine easier to do .
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.
By using Euclid's formula this problem can be made easier:
a = (m*m - n * n)
b = 2mn
c = (m*m + n * n)
where m > n
then by solving a + b + c = 1000 we get
n = (500 - m*m)/m
So with this forumla m must be greater than 15 but less then 22
F#
[for m in 16..21 -> (m,(500-(m*m))/m)]
|> List.map (fun (m,n) -> (m*m - n*n, 2*m*n, m*m + n*n))
|> List.find(fun (a,b,c) -> a + b + c = 1000)
|> (fun (a,b,c)-> a * b * c)
|> print_any
C#
var mnTuple = Enumerable.Range(16, 7).Select(x => new { m = x, n = (500 - (x * x)) / x });
var abcTuple = mnTuple.Select(x => new { a = x.m * x.m - x.n * x.n, b = 2 * x.m * x.n, c = x.m * x.m + x.n * x.n });
var triplet = abcTuple.Where(x => x.a + x.b + x.c == 1000).First();
var value = triplet.a * triplet.b * triplet.c;
Console.WriteLine(value);
Console.ReadLine();
del.icio.us Tags:
F#,
C#,
Project Euler,
Linq