How to find the first Pythagorean triple in Java

1 Answer

0 votes
/**
A Pythagorean triple is a set of three positive integers (a, b, c)
that satisfy the Pythagorean theorem:

        a^2 + b^2 = c^2

These represent the side lengths of a right triangle.
The smallest and most famous Pythagorean triple is (3, 4, 5).
*/

public class FirstPythagoreanTriple {

    // Function to find the first Pythagorean triple
    public static void findFirstPythagoreanTriple() {
        for (int a = 1; a <= 100; a++) {
            for (int b = a; b <= 100; b++) {
                int c2 = a * a + b * b;   // c^2
                int c = (int) Math.sqrt(c2);

                if (c * c == c2) {        // Check if c is an integer
                    System.out.println("First Pythagorean triple: " + a + ", " + b + ", " + c);
                    return;
                }
            }
        }
    }

    public static void main(String[] args) {
        findFirstPythagoreanTriple();
    }
}


/*
run:

First Pythagorean triple: 3, 4, 5

*/

 



answered 3 days ago by avibootz
...