A Pythagorean triplet is a set of three natural numbers, a
b
c, for which,
a2 + b 2 = c 2For 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.
Algebra time. I had to go back to the formal definition for ALL triplets. Its easy to confuse formulae that only create some, not all.
Just created nested loops to run through k, n & m and calculate:
a = k * (Math.pow(m,2) – Math.pow(n,2));
b = k * (2 * m * n);
c = k * (Math.pow(m,2) + Math.pow(n,2));
then test each to see if the sum is 1000.
public class Euler9
{
public static void main(String[] args)
{
System.out.print(“Problem 9:\n”);
Euler9 e = new Euler9();
System.out.print(“Answer = ” + e.Problem()+ “\n”);
}
public String Problem ()
{
double a = 0;
double b = 0;
double c = 0;
double product = 0;
for (int k = 1; k <=100; k++)
{
for (int n = 1; n <= 100; n++)
{
for (int m = 1; m <= 100; m++)
{
if (m > n)
{
a = k * (Math.pow(m,2) – Math.pow(n,2));
b = k * (2 * m * n);
c = k * (Math.pow(m,2) + Math.pow(n,2));
if (a+b+c == 1000 && a > 0 && b > 0 && c > 0)
{
product = a * b * c;
System.out.print(“k:” + k +” n:” + n+ ” m:” + m + ” a:” + a +” b:” + b+ ” c:” + c + “\n”);
}
}
}
}
}
return String.format(“%.0f”, product);
}
}