Count number of pairs (i, j) such that arr[i] * arr[j] > arr[i] + arr[j] in C++


We are given an array of n positive numbers.The goal is to count the ordered pairs (i,j) such that arr[i]*arr[j] > arr[i]+arr[j] and 0<=i<j<n. Where n is the number of elements in the array.

We will traverse the array using two for loops for each number of pairs. Now calculate the sum and product of arr[i] and arr[j]. If the product is greater than sum increment count.

Let’s understand with examples.

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

Output − Count of pairs − 1

Explanation − Only valid pair is − (2,3)

2*3=6 > 2+3=5

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

Output − Count of pairs − 0

Explanation − both 2*2 and 2+2 is 4. No pairs where product>sum

Approach used in the below program is as follows

  • We take an integer array arr[] initialized with positive numbers.

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

  • Function countPairs(int arr[], int n) takes an array, its length as input and prints the count of pairs with product>sum.

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

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

  • Check if arr[i]*arr[j]>arr[i]+arr[j]. Increment count if true.

  • At the end of all loops count will have a total number of pairs that have product > sum

  • Return 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;
   for(int i=0;i<n-1;i++){
      for(int j=i+1;j<n;j++){
         if(arr[i]*arr[j]>arr[i]+arr[j]) //condition
            { count++; }
      }
   }
   return count;
}
int main(){
   int arr[] = { 1,2,3,2 };
   int len = sizeof(arr) / sizeof(int);
   cout<<"Count of number of pairs :"<<countPairs(arr, len);
   return 0;
}

Output

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

Count of number of pairs :2

Updated on: 29-Aug-2020

520 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements