Count of pairs in an array whose sum is a perfect square in C++


We are given with an array of N elements. The goal is to find the count of all pairs (Arr[i],Arr[j]) which have a sum which is a perfect square such that i!=j. That is Arr[i]+Arr[j] is a perfect square.

We will do this by calculating the sum of pairs and check if the square root of that sum is equal to the floor value of the square root. sqrt(Arr[i]+Arr[j])-floor( sqrt(Arr[i]+Arr[j] )==0.

Let’s understand with examples.

Input − Arr[]= { 4,3,2,1,2,4 } N=6

Output − Count of pairs with sum as perfect square − 2

Explanation

Arr[1]+Arr[3]=4, sqrt(4)-floor(4)=0 4 is a perfect square.
Arr[2]+Arr[4]=4, sqrt(4)-floor(4)=0 4 is a perfect square.
Rest all pairs have sum 7,6,5,8 which are not perfect squares.

Input − Arr[]= { 3,3,3,3,3} N=5

Output − Count of pairs with sum as perfect square − 0

Explanation − All pairs have sum=6, which is not a perfect square.

Approach used in the below program is as follows

  • We take an integer array Arr[] initialized with random numbers for size of gloves > 0.

  • Take a variable n which stores the length of Arr[].

  • Function countPairs(int arr[], int n) takes an array, its length as input and returns the pairs which have sum which is a perfect square.

  • Traverse array using two for loops for each element of the pair.

  • Outer Loop from 0<=i<n-1, inner loop i<j<n

  • Calculate sum of arr[i], arr[j] are positive.

  • Calculate square root of sum as sqrt(sum).

  • Now check if sqr-floor(sqr)==0. Which means sum is a perfect square. If true increment count.

  • At the end of all loops count will have a total number of pairs that have sum which is perfect square.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int countPairs(int arr[], int n){
   int count=0;
   int sum=0;
   double sqr=0;
   for(int i=0;i<n-1;i++){
      for(int j=i+1;j<n;j++){
         sum=arr[i]+arr[j];
         sqr=sqrt(sum);
         if( sqr-floor(sqr)==0 ){
            count++;
            //cout<<endl<<"a :"<<arr[i]<<" b :"<<arr[j]; //to print
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 1, 2, 4, 8, 5, 6 };
   // Size of arr[]
   int n = sizeof(arr) / sizeof(int);
   cout <<endl<<"Pairs whose sum is perfect square :"<<countPairs(arr, n);
   return 0;
}

Output

If we run the above code it will generate the following output −

Pairs whose sum is perfect square :2

Updated on: 29-Aug-2020

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements