Find all pairs (a, b) in an array such that a % b = k
Last Updated :
15 Sep, 2023
Given an array with distinct elements, the task is to find the pairs in the array such that a % b = k, where k is a given integer.
Examples :
Input : arr[] = {2, 3, 5, 4, 7}
k = 3
Output : (7, 4), (3, 4), (3, 5), (3, 7)
7 % 4 = 3
3 % 4 = 3
3 % 5 = 3
3 % 7 = 3
A Naive Solution is to make all pairs one by one and check their modulo is equal to k or not. If equals to k, then print that pair.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool printPairs( int arr[], int n, int k)
{
bool isPairFound = true ;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (i != j && arr[i] % arr[j] == k) {
cout << "(" << arr[i] << ", "
<< arr[j] << ")"
<< " " ;
isPairFound = true ;
}
}
}
return isPairFound;
}
int main()
{
int arr[] = { 2, 3, 5, 4, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
if (printPairs(arr, n, k) == false )
cout << "No such pair exists" ;
return 0;
}
|
Java
class Test {
static boolean printPairs( int arr[], int n, int k)
{
boolean isPairFound = true ;
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < n; j++) {
if (i != j && arr[i] % arr[j] == k) {
System.out.print( "(" + arr[i] + ", " + arr[j] + ")"
+ " " );
isPairFound = true ;
}
}
}
return isPairFound;
}
public static void main(String args[])
{
int arr[] = { 2 , 3 , 5 , 4 , 7 };
int k = 3 ;
if (printPairs(arr, arr.length, k) == false )
System.out.println( "No such pair exists" );
}
}
|
Python3
def printPairs(arr, n, k):
isPairFound = True
for i in range ( 0 , n):
for j in range ( 0 , n):
if (i ! = j and arr[i] % arr[j] = = k):
print ( "(" , arr[i], ", " , arr[j], ")" ,
sep = " ", end = " ")
isPairFound = True
return isPairFound
arr = [ 2 , 3 , 5 , 4 , 7 ]
n = len (arr)
k = 3
if (printPairs(arr, n, k) = = False ):
print ( "No such pair exists" )
|
C#
using System;
public class GFG {
static bool printPairs( int [] arr, int n, int k)
{
bool isPairFound = true ;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++)
{
if (i != j && arr[i] % arr[j] == k)
{
Console.Write( "(" + arr[i] + ", "
+ arr[j] + ")" + " " );
isPairFound = true ;
}
}
}
return isPairFound;
}
public static void Main()
{
int [] arr = { 2, 3, 5, 4, 7 };
int k = 3;
if (printPairs(arr, arr.Length, k) == false )
Console.WriteLine( "No such pair exists" );
}
}
|
PHP
<?php
function printPairs( $arr , $n , $k )
{
$isPairFound = true;
for ( $i = 0; $i < $n ; $i ++)
{
for ( $j = 0; $j < $n ; $j ++)
{
if ( $i != $j && $arr [ $i ] %
$arr [ $j ] == $k )
{
echo "(" , $arr [ $i ] , ", " ,
$arr [ $j ] , ")" , " " ;
$isPairFound = true;
}
}
}
return $isPairFound ;
}
$arr = array (2, 3, 5, 4, 7);
$n = sizeof( $arr );
$k = 3;
if (printPairs( $arr , $n , $k ) == false)
echo "No such pair exists" ;
?>
|
Javascript
<script>
function printPairs(arr, n, k)
{
let isPairFound = true ;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++)
{
if (i != j && arr[i] % arr[j] == k)
{
document.write( "(" + arr[i] + ", " + arr[j] + ")" + " " );
isPairFound = true ;
}
}
}
return isPairFound;
}
let arr = [ 2, 3, 5, 4, 7 ];
let k = 3;
if (printPairs(arr, arr.length, k) == false )
document.write( "No such pair exists" );
</script>
|
Output
(3, 5) (3, 4) (3, 7) (7, 4)
Time Complexity : O(n2)
Auxiliary Space: O(1)
An Efficient solution is based on below observations :
- If k itself is present in arr[], then k forms a pair with all elements arr[i] where k < arr[i]. For all such arr[i], we have k % arr[i] = k.
- For all elements greater than or equal to k, we use the following fact.
If arr[i] % arr[j] = k,
==> arr[i] = x * arr[j] + k
==> (arr[i] - k) = x * arr[j]
We find all divisors of (arr[i] - k)
and see if they are present in arr[].
To quickly check if an element is present in the array, we use hashing.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > findDivisors( int n)
{
vector< int > v;
for ( int i = 1; i <= sqrt (n); i++) {
if (n % i == 0) {
if (n / i == i)
v.push_back(i);
else {
v.push_back(i);
v.push_back(n / i);
}
}
}
return v;
}
bool printPairs( int arr[], int n, int k)
{
unordered_map< int , bool > occ;
for ( int i = 0; i < n; i++)
occ[arr[i]] = true ;
bool isPairFound = false ;
for ( int i = 0; i < n; i++) {
if (occ[k] && k < arr[i]) {
cout << "(" << k << ", " << arr[i] << ") " ;
isPairFound = true ;
}
if (arr[i] >= k) {
vector< int > v = findDivisors(arr[i] - k);
for ( int j = 0; j < v.size(); j++) {
if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) {
cout << "(" << arr[i] << ", "
<< v[j] << ") " ;
isPairFound = true ;
}
}
v.clear();
}
}
return isPairFound;
}
int main()
{
int arr[] = { 3, 1, 2, 5, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 2;
if (printPairs(arr, n, k) == false )
cout << "No such pair exists" ;
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Vector;
class Test {
static Vector<Integer> findDivisors( int n)
{
Vector<Integer> v = new Vector<>();
for ( int i = 1 ; i <= Math.sqrt(n); i++) {
if (n % i == 0 ) {
if (n / i == i)
v.add(i);
else {
v.add(i);
v.add(n / i);
}
}
}
return v;
}
static boolean printPairs( int arr[], int n, int k)
{
HashMap<Integer, Boolean> occ = new HashMap<>();
for ( int i = 0 ; i < n; i++)
occ.put(arr[i], true );
boolean isPairFound = false ;
for ( int i = 0 ; i < n; i++) {
if (occ.get(k) && k < arr[i]) {
System.out.print( "(" + k + ", " + arr[i] + ") " );
isPairFound = true ;
}
if (arr[i] >= k) {
Vector<Integer> v = findDivisors(arr[i] - k);
for ( int j = 0 ; j < v.size(); j++) {
if (arr[i] % v.get(j) == k && arr[i] != v.get(j) && occ.get(v.get(j))) {
System.out.print( "(" + arr[i] + ", "
+ v.get(j) + ") " );
isPairFound = true ;
}
}
v.clear();
}
}
return isPairFound;
}
public static void main(String args[])
{
int arr[] = { 3 , 1 , 2 , 5 , 4 };
int k = 2 ;
if (printPairs(arr, arr.length, k) == false )
System.out.println( "No such pair exists" );
}
}
|
Python3
import math as mt
def findDivisors(n):
v = []
for i in range ( 1 , mt.floor(n * * (. 5 )) + 1 ):
if (n % i = = 0 ):
if (n / i = = i):
v.append(i)
else :
v.append(i)
v.append(n / / i)
return v
def printPairs(arr, n, k):
occ = dict ()
for i in range (n):
occ[arr[i]] = True
isPairFound = False
for i in range (n):
if (occ[k] and k < arr[i]):
print ( "(" , k, "," , arr[i], ")" , end = " " )
isPairFound = True
if (arr[i] > = k):
v = findDivisors(arr[i] - k)
for j in range ( len (v)):
if (arr[i] % v[j] = = k and
arr[i] ! = v[j] and
occ[v[j]]):
print ( "(" , arr[i], "," , v[j],
")" , end = " " )
isPairFound = True
return isPairFound
arr = [ 3 , 1 , 2 , 5 , 4 ]
n = len (arr)
k = 2
if (printPairs(arr, n, k) = = False ):
print ( "No such pair exists" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static List< int > findDivisors( int n)
{
List< int > v = new List< int >();
for ( int i = 1;
i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
if (n / i == i)
{
v.Add(i);
}
else
{
v.Add(i);
v.Add(n / i);
}
}
}
return v;
}
public static bool printPairs( int [] arr,
int n, int k)
{
Dictionary< int ,
bool > occ = new Dictionary< int ,
bool >();
for ( int i = 0; i < n; i++)
{
occ[arr[i]] = true ;
}
bool isPairFound = false ;
for ( int i = 0; i < n; i++)
{
if (occ[k] && k < arr[i])
{
Console.Write( "(" + k + ", " +
arr[i] + ") " );
isPairFound = true ;
}
if (arr[i] >= k)
{
List< int > v = findDivisors(arr[i] - k);
for ( int j = 0; j < v.Count; j++)
{
if (arr[i] % v[j] == k &&
arr[i] != v[j] && occ[v[j]])
{
Console.Write( "(" + arr[i] +
", " + v[j] + ") " );
isPairFound = true ;
}
}
v.Clear();
}
}
return isPairFound;
}
public static void Main( string [] args)
{
int [] arr = new int [] {3, 1, 2, 5, 4};
int k = 2;
if (printPairs(arr, arr.Length, k) == false )
{
Console.WriteLine( "No such pair exists" );
}
}
}
|
Javascript
<script>
function findDivisors(n)
{
let v = [];
for (let i = 1; i <= Math.sqrt(n); i++)
{
if (n % i == 0) {
if (n / i == i)
v.push(i);
else {
v.push(i);
v.push(Math.floor(n / i));
}
}
}
return v;
}
function printPairs(arr,n,k)
{
let occ = new Map();
for (let i = 0; i < n; i++)
occ.set(arr[i], true );
let isPairFound = false ;
for (let i = 0; i < n; i++) {
if (occ.get(k) && k < arr[i]) {
document.write( "(" + k + ", " +
arr[i] + ") " );
isPairFound = true ;
}
if (arr[i] >= k) {
let v = findDivisors(arr[i] - k);
for (let j = 0; j < v.length; j++)
{
if (arr[i] % v[j] == k &&
arr[i] != v[j] &&
occ.get(v[j]))
{
document.write( "(" + arr[i] + ", "
+ v[j] + ") " );
isPairFound = true ;
}
}
v=[];
}
}
return isPairFound;
}
let arr=[3, 1, 2, 5, 4 ];
let k = 2;
if (printPairs(arr, arr.length, k) == false )
document.write( "No such pair exists" );
</script>
|
Output
(2, 3) (2, 5) (5, 3) (2, 4)
Time Complexity: O(n* sqrt(max)) where max is the maximum element in the array.
Auxiliary Space: O(n)
This article is contributed by Aarti_Rathi and Sahil Chhabra.
Please Login to comment...