Count divisible pairs in an array in C++

C++Server Side ProgrammingProgramming

We are given an array of any size containing integer elements and the task is to calculate the count of pairs in an array such that one element of a pair divides another element of a pair.

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

For Example

Input − int arr[] = {1, 2, 3, 6}
Output − count is 4

Explanation − (1,2), (1,3), (1,6) and (3,6) are the pairs in which one element of a pair divides another as 1 can divide any number and also 3 divides 6. So the count is 4.

Input − int arr[] = {2, 5, 10}
Output − count is 2

Explanation − (2, 10) and (5,10) are the pairs in which one element of a pair divides another as 2 can divide 10 and also 5 can divide 10. So the count is 2.

Approach used in the below program is as follows

  • Create an array let’s say, arr[]

  • Calculate the length of an array using the length() function that will return an integer value as per the elements in an array.

  • Take a temporary variable that will store the count of elements present only in an array.

  • Start loop for with i to 0 and i less than size of an array

  • Inside the loop start another loop with j to i+1 till j less than size

  • Inside the loop check if arr[i] % arr[j] = 0 or arr[j] % arr[i] = 0 then increment the count

  • Return the count

  • Print the result.

Example

 Live Demo

#include <iostream>
using namespace std;
int divisibles(int a[], int size){
   int result = 0;
   // Iterating through all pairs
   for (int i=0; i<size; i++){
      for (int j=i+1; j<size; j++){
         if (a[i] % a[j] == 0 || a[j] % a[i] == 0){
            result++;
         }
      }
   }
   return result;
}
int main(){
   int a[] = {1, 4, 7, 8, 9};
   int size = sizeof(a) / sizeof(a[0]);
   cout <<"count is " <<divisibles(a, size);
   return 0;
}

Output

If we run the above code we will get the following output −

count is 5
raja
Published on 15-May-2020 15:16:16
Advertisements