- Related Questions & Answers
- Count of index pairs with equal elements in an array in C++
- Count all pairs of an array which differ in K bits in C++
- K-diff Pairs in an Array in C++
- Count of pairs in an array whose sum is a perfect square in C++
- Count of pairs (x, y) in an array such that x < y in C++
- Count valid pairs in the array satisfying given conditions in C++
- Count pairs with given sum in C++
- Count pairs with Odd XOR in C++
- Array of Doubled Pairs in C++
- K Inverse Pairs Array in C++
- Sum of XOR of all pairs in an array in C++
- Count distinct elements in an array in C++
- Count all pairs with given XOR in C++
- Count number of distinct pairs whose sum exists in the given array in C++
- Find the maximum cost of an array of pairs choosing at most K pairs in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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.

#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; }

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

count is 5

Advertisements