This is the Java Program to Check if There are Any Pythagorean Triplets in the Array.
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:
Array = [1, 3, 4, 5]
Output: 3, 4 and 5
Use three nested loops, and inside the innermost loop, check for the array elements satisfying the Pythagorean triplet equivalence, or not.
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PythagoreanTriplets {
// Function to find and display Pythagorean triplets
static void printPythagoreanTriplets(int[] array){
int i,j,k;
int x,y,z;
int count=0;
for(i=0;i<array.length;i++){
x=array[i];
for(j=0;j<array.length;j++){
y=array[j];
for(k=0;k<array.length;k++){
z=array[k];
if((z*z)==(x*x + y*y)){
count++;
System.out.println(x+", "+y+", "+z);
return;
}
}
}
}
System.out.println("No pythagorean triplets exist in the array");
}
// Function to read user input
public static void main(String[] args) {
int size;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the array size");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Size");
return;
}
int[] array = new int[size];
int i;
System.out.println("Enter array elements");
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
}
}
printPythagoreanTriplets(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.
Case 1 (Positive Test Case): Enter the array size 4 Enter array elements 1 3 4 5 3, 4, and 5 Case 2 (Negative Test Case): Enter the array size 4 Enter array elements 1 2 3 4 No pythagorean triplets exist in the array
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice BCA MCQs
- Practice Programming MCQs
- Apply for Java Internship
- Check Java Books
- Practice Information Technology MCQs