Find All Pairs (A, B) in an Array Such That A - B = K in C++



Suppose we have an array A, from that array, we have to get all pairs (a, b) such that the a%b = k. Suppose the array is A = [2, 3, 4, 5, 7], and k = 3, then pairs are (7, 4), (3, 4), (3, 5), (3, 7).

To solve this, we will traverse the list and check whether the given condition is satisfying or not.

Example

 Live Demo

#include <iostream>
using namespace std;
bool displayPairs(int arr[], int n, int k) {
   bool pairAvilable = true;
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
         if (arr[i] % arr[j] == k) {
            cout << "(" << arr[i] << ", "<< arr[j] << ")"<< " ";
            pairAvilable = true;
         }
      }
   }
   return pairAvilable;
}
int main() {
   int arr[] = { 2, 3, 4, 5, 6, 7 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 3;
   if (displayPairs(arr, n, k) == false)
      cout << "No paira found";
}

Output

(3, 4) (3, 5) (3, 6) (3, 7) (7, 4)
Updated on: 2019-10-24T13:15:12+05:30

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements