Code for finding pythagorean triplets

I am currently attempting this question :

A Pythagorean triplet is a set of three natural numbers, a, b and 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.

My code is as follows, I think it should be correct, but the site is telling me my answer is wrong? Can someone help me see the flaws in my logic please?

public class Pythagoras {
    public static void main(String[] args) {
            int sum = 1000;
            int a;
            int product=0;
            for (a = 1; a <= sum/3; a++)
            {
                int b;
                for (b = a + 1; b <= sum/2; b++)
                {
                    int c = sum - a - b;
                    if ( c > 0 && (a*a + b*b == c*c) )
                       System.out.printf("a=%d, b=%d, c=%dn",a,b,c);
                        product = a * b * c;
                }
            }
            System.out.println(product);
        }
    }

Answer

I think you’re missing a set of braces. The indentation leads me to believe the two innermost statements go together but you need curly braces for that to be correct.

if ( c > 0 && (a*a + b*b == c*c) )
{
    System.out.printf("a=%d, b=%d, c=%dn",a,b,c);
    product = a * b * c;
}

Without the braces product will always contain the product of the last values of a, b, and c. (333 * 500 * 167 == 27805500).

Leave a Reply

Your email address will not be published. Required fields are marked *