Euler Problem 9

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.

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);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s