- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i] in C++
We are given with an array arr[] of N elements. The goal is to find the count of all valid pairs of indexes (i,j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i] and i!=j.
We will do this by traversing the array arr[] using two for loops for each number of pair and check if arr[i]%arr[j]==0 or arr[j]%arr[i]==0 when i!=j. If true increment count of pairs.
Let’s understand with examples.
Input − Arr[]= { 2,4,3,6 } N=4
Output − Count of valid pairs − 3
Explanation − Valid pairs are −
Arr[0] & Arr[1] → (2,4) here 4%2==0 0!=1 Arr[0] & Arr[1] → (2,6) here 6%2==0 0!=3 Arr[2] & Arr[3] → (3,6) here 6%3==0 2!=3
Input − Arr[]= { 2,5,7,9,11 } N=5
Output− Count of valid pairs − 0
Explanation − No number fully divides the other. No pair can be formed.
Approach used in the below program is as follows
We take an integer array Arr[] initialized with random 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 returns the pairs which are valid and meet desired conditions.
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]==0 or arr[j]%arr[i]==0. Increment count once if either of condition is true.
At the end of all loops count will have a total number of pairs that are valid
Return the count as result.
Example
#include <bits/stdc++.h> using namespace std; int countPairs(int arr[], int n){ // Count of pairs int count = 0; for (int i = 0; i < n-1; i++){ for (int j = i + 1; j < n; j++){ if(arr[i]%arr[j]==0 || arr[j]%arr[i]==0) { count++; } } } return count; } int main(){ int Arr[] = { 2,3,4,5,6 }; int len = sizeof(Arr) / sizeof(Arr[0]); 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 : 3