Special Pythagorean Triplet

179 Views Asked by At

What's wrong with my code? It prints 2,2 when the correct answer is clearly 6,8

public static void main(String[] args) {

    int a = 1;
    int b = 1;
    int answer = 0;
    int j = 4;
    while (j == 4) {
        for (a = 1; a <= 10; a++) {
            for (b = 1; b <= 10; b++) {
                answer = a * a + b * b;
                if (answer == 100) {
                    j = 10;
                }
            }
        }
    }
    System.out.println(a + " " + b);
}
2

There are 2 best solutions below

2
On

if(answer == 100); you have an extra semicolon after your if.

This will cause it to execute the j = 10; no matter what answer equals

2
On

You are incrementing a and b at the same time. In your code, the two numbers will always be equal. Also, you are not testing for a match when you exit the loop.