-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind_pythagorean_triplet_in_array.cpp
More file actions
41 lines (39 loc) · 1.03 KB
/
find_pythagorean_triplet_in_array.cpp
File metadata and controls
41 lines (39 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>
#include<math.h>
using namespace std;
bool findTriplet(int a[], int n)
{
// Squaring all the elements in the array
for (int i=0; i<n; i++)
a[i] = a[i]*a[i];
// Sorting the array
sort(a, a + n);
// Now, We'll fix one element in each iteration and find the other two elements
for (int i = n-1; i >= 2; i--)
{
int j = 0;
int k = i-1;
while (j < k)
{
if (a[j] + a[k] == a[i])
{
cout<<"The pythagorean triplet present in the given array is ("<<sqrt(a[j])<<","<<sqrt(a[k])<<","<<sqrt(a[i])<<").";
return true;
}
(a[j]+a[k] < a[i])? j++: k--;
}
}
return false;
}
int main()
{
int A[200], N, i;
cout<<"Enter total no. of elements to be sorted: ";
cin>>N;
cout<<"Enter the elements of array: "<<endl;
for(i=0;i<N;i++)
cin>>A[i];
if (!findTriplet(A, N))
cout<<"No Pythagorean Triplet preesent in the given array";
return 0;
}