This program checks if the pythogorean triplet exist in an array or not i.e a^2+b^2 = c^2

Example:

Let A[] = { 14, 2, 1, 5,  12, 8, 9, 13}

a=12, b=5, c=13.. Now, 144+25=169.... it means pythagorean triplet exist in the array.

Algorithm:

 

step 1:  First sort the array
step 2:  Do square of every element of the array from arr[0] to arr[n-1]
step 3:  For i=n-1 to 2:
step 4:             set: c=arr[i]
step 5:             set: j=0
step 6:             set: k=i-1
step 7:             check for pair in array whose sum equals to c.. If you don't know how
                        to find .. click here
step 8:             if(pair is found):  return true
step 9:  EndFor
step 10: return false
 

Time complexity: O(n*n)

Program:
 


#include <iostream>
#include <stdio.h>
using namespace std;
bool check(int arr[],int n);
int main() {
 
     int n,arr[100];
        printf("\nEnter the number of elements in array: ");
     scanf("%d",&n);

        printf("\nEnter the elements of array: \n");
     for(int j=0;j<n;j++)
     {
         scanf("%d",&arr[j]);
     }
     if(check(arr,n))
     {
            printf("\n");
         printf("Yes");
     }
     else
     {  
            printf("\n");
         printf("No");
     }
     printf("\n");
 
 return 0;
}
bool check(int arr[],int n)
{
     for(int i=0;i<n;i++)
     {
         arr[i]=arr[i]*arr[i];
     }
     int key,j;
     for(int i=1;i<n;i++)
     {
         key=arr[i];
         j=i-1;
         while(arr[j]>key && j>=0)
         {
             arr[j+1]=arr[j];
             j=j-1;
         }
         arr[j+1]=key;
     }
     for(int i=n-1;i>=2;i--)
     {
         int a=arr[i];
         j=0;
         int k=i-1;
         while(j<k)
         {
             if(arr[j]+arr[k]==a)
             {
                 return true;
             }
             else if(arr[j]+arr[k]>a)
             {
                 k--;
             }
             else if(arr[j]+arr[k]<a)
             {
                 j++;
             }
         }
     }
     return false;
}

OUTPUT: