Skip to content
Advertisement

All Pythagorean Triplets in a range

If I want to find all the Pythagorean Triplets in a specific range, I wrote the following code:

for (int a = 1; a < range; a++) {
        for (int b = 1; b < range; b++) {
            for (int c = 1; c < range; c++) {
                if (a * a + b * b == c * c) {
                    System.out.println(a + "," + b + "," + c);
                }
            }
        }
    }

But unfortunately I got duplicated triplets, for example: 3, 4, 5 and 4, 3, 5
How can I overcome this?

Advertisement

Answer

You can remove duplicates by changing your loops, particularly where each one starts:

for (int a = 1; a < range; a++) {
        for (int b = a + 1; b < range; b++) {
            for (int c = b + 1; c < range; c++) {
                if (a * a + b * b == c * c) {
                    System.out.println(a + "," + b + "," + c);
                }
            }
        }
    }

Notice that the inner loop is unnecessary since you can calculate c directly from a and b. You just have to check if the calculated value is an integer:

for (int a = 1; a < range; a++) {
        for (int b = a + 1; b < range; b++) {
            double c = Math.sqrt(a*a + b*b)
            if (c == int(c)) {
                System.out.println(a + "," + b + "," + c);
            }
        }
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement