Java Program to Check if There are Any Pythagorean Triplets in the Array

This is the Java Program to Check if There are Any Pythagorean Triplets in the Array.

Problem Description

Given an array of integers, check for any triplet of elements say a, b, and c where all three elements form a Pythagorean triplet, that is, c2 = a2 + b2
Example:

advertisement

Array = [1, 3, 4, 5]

Output: 3, 4 and 5

Problem Solution

Use three nested loops, and inside the innermost loop, check for the array elements satisfying the Pythagorean triplet equivalence, or not.

Program/Source Code

advertisement

Here is the source code of the Java Program to Check if There are Any Pythagorean Triplets in the Array. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

//Java Program to Check if There are Any Pythagorean Triplets in the Array

1. In function printPythagoreanTriplets(), triple nested loops are used to check every combination of array elements.
2. If any combination of elements satisfies the Pythagorean triplet criteria if((z*z)==(x*x + y*y)), then that triplet is printed and we return from the function.
3. If Pythagorean triplet existed, then a suitable message is displayed.