Computer >> Computer tutorials >  >> Programming >> C++

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

#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)