Task: Given an array of integers, If a, b, c are integers in an array and satisfies the Pythagorean formulae : a^2 + b^2 = c^2 then print Yes else print No.
Example:
Input:
1
5
3 2 4 1 5
Output:
Yes // 3,4, and 5 are Pythagorean Triplets.
Here is the Code:
Program in C++:
- #include<iostream>
 - #include<bits/stdc++.h>
 - using namespace std;
 - string pythagoreanTriplet(int *a,int n)
 - {
 - set<int> s;
 - for(int i=0;i<n;i++)
 - {
 - a[i]=a[i]*a[i];
 - s.insert(a[i]);
 - }
 - sort(a,a+n);
 - // 4 9 16 25 36
 - for(int i=n-1;i>=2;i--)
 - {
 - int j=0;
 - while(j<i)
 - {
 - if(s.find(a[i]-a[j])!=s.end()) return "Yes";
 - auto k = s.find(a[i]-a[j]);
 - if(*k+a[j]>a[i]) break;
 - j++;
 - }
 - }
 - return "No";
 - }
 - int main()
 - {
 - int t;
 - cin>>t;
 - while(t--)
 - {
 - int n;
 - cin>>n;
 - int a[n];
 - for(int i=0;i<n;i++)
 - {
 - cin>>a[i];
 - }
 - cout<<pythagoreanTriplet(a,n)<<endl;
 - }
 - return 0;
 - }
 
Here is the Video:
Comments
Post a Comment