





Please login
Prime

Prepinsta Prime
Video courses for company/skill based Preparation
(Check all courses)
Get Prime Video
Prime

Prepinsta Prime
Purchase mock tests for company/skill building
(Check all mocks)
Get Prime mock
Finding pythagorean triplets in an array

Finding Pythagorean triplets in an array in Java.
Problem Statement:
we have an array of integers, write a function that will returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
Example:
Input: arr[ ] = {3, 1, 4, 6, 5}
Output: True
Algorithm:
- Start
- Run three loops to find three triplets
- satisfy the condition (a2+b2=c2)
- print the triplets
- End
Java code :
// A Java program that returns true if there is a Pythagorean
import java.io.*;
class prepinsta {
static boolean isTriplet(int ar[], int n)
{
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
// Calculate square of array elements
int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k];
if (x == y + z || y == x + z || z == x + y)
return true;
}
}
}
// If we reach here, no triplet found
return false;
}
public static void main(String[] args)
{
int ar[] = { 3, 1, 4, 6, 5 };
int ar_size = ar.length;
if (isTriplet(ar, ar_size) == true)
System.out.println(“Yes triplets are there”);
else
System.out.println(“No triplets are not there “);
}
}
Output:
Yes triplets are there
Login/Signup to comment