Pair of integers having least GCD among all given pairs having GCD exceeding K

Given an array arr[][] containing pairs of integers in increasing order of GCDs, and an integer K, the task is to find a pair of integers whose GCD is at least K and is also the least among all possible GCDs exceeding K. If there exists no such pair, then print -1.
Examples:

Input: arr[][] = [(3, 6), (15, 30), (25, 75), (30, 120)], K = 16 
Output: (25, 75) 
Explanation: 
The GCD of (25, 75) is 25 which is greater than 16 and least among all possible GCD.

Input: arr[] = [(2, 5), (12, 36), (13, 26)], K = 14 
Output: -1

Naive Approach: The simplest approach is to iterate over all the pairs of the given array and check for each pair, if its GCD exceeds K. From all such pairs, print the pair having the least GCD.

Time Complexity: O(N * log(N)) 
Auxiliary Space: O(1)

Efficient Approach: The idea is to observe that the array elements are sorted in increasing order of their GCD values of the pair so use Binary Search. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate
// the GCD of two numbers
int GCD(int a, int b)
{
    if (b == 0) {
        return a;
    }
    return GCD(b, a % b);
}
 
// Function to print the pair
// having a gcd value just greater
// than the given integer
void GcdPair(vector<pair<int, int> > arr, int k)
{
    // Initialize variables
    int lo = 0, hi = arr.size() - 1, mid;
    pair<int, int> ans;
    ans = make_pair(-1, 0);
 
    // Itertae until low less
    // than equal to high
    while (lo <= hi) {
 
        // Calculate mid
        mid = lo + (hi - lo) / 2;
        if (GCD(arr[mid].first,
                arr[mid].second)
            > k) {
            ans = arr[mid];
            hi = mid - 1;
        }
        // Reducing the search space
        else
            lo = mid + 1;
    }
 
    // Print the answer
    if (ans.first == -1)
        cout << "-1";
    else
        cout << "( " << ans.first << ", "
             << ans.second << " )";
 
    return;
}
 
// Driver Code
int main()
{
    // Given array and K
    vector<pair<int, int> > arr = { { 3, 6 },
                                    { 15, 30 },
                                    { 25, 75 },
                                    { 30, 120 } };
    int K = 16;
 
    // Function Call
    GcdPair(arr, K);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Function to calculate
// the GCD of two numbers
static int GCD(int a, int b)
{
  if (b == 0)
  {
    return a;
  }
  return GCD(b, a % b);
}
 
// Function to print the pair
// having a gcd value just
// greater than the given integer
static void GcdPair(int [][]arr,
                    int k)
{
  // Initialize variables
  int lo = 0, hi = arr.length - 1, mid;
  int []ans = {-1, 0};
 
  // Iterate until low less
  // than equal to high
  while (lo <= hi)
  {
    // Calculate mid
    mid = lo + (hi - lo) / 2;
    if (GCD(arr[mid][0],
            arr[mid][1]) > k)
    {
      ans = arr[mid];
      hi = mid - 1;
    }
     
    // Reducing the search space
    else
      lo = mid + 1;
  }
 
  // Print the answer
  if (ans[0] == -1)
    System.out.print("-1");
  else
    System.out.print("( " + ans[0] +
                     ", " + ans[1] + " )");
  return;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array and K
  int [][]arr = {{3, 6},
                 {15, 30},
                 {25, 75},
                 {30, 120}};
  int K = 16;
 
  // Function Call
  GcdPair(arr, K);
}
}
 
// This code is contributed by 29AjayKumar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to calculate
# the GCD of two numbers
def GCD(a, b):
     
    if (b == 0):
        return a
         
    return GCD(b, a % b)
 
# Function to prthe pair
# having a gcd value just greater
# than the given integer
def GcdPair(arr, k):
     
    # Initialize variables
    lo = 0
    hi = len(arr) - 1
    ans = [-1, 0]
 
    # Itertae until low less
    # than equal to high
    while (lo <= hi):
 
        # Calculate mid
        mid = lo + (hi - lo) // 2
        if (GCD(arr[mid][0], arr[mid][1]) > k):
            ans = arr[mid]
            hi = mid - 1
 
        # Reducing the search space
        else:
            lo = mid + 1
 
    # Print the answer
    if (len(ans) == -1):
        print("-1")
    else:
        print("(", ans[0], ",", ans[1], ")")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array and K
    arr = [ [ 3, 6 ],
            [ 15, 30 ],
            [ 25, 75 ],
            [ 30, 120 ] ]
    K = 16
 
    # Function call
    GcdPair(arr, K)
 
# This code is contributed by mohit kumar 29
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for
// the above approach
using System;
class GFG{
 
// Function to calculate
// the GCD of two numbers
static int GCD(int a, int b)
{
  if (b == 0)
  {
    return a;
  }
  return GCD(b, a % b);
}
 
// Function to print the pair
// having a gcd value just
// greater than the given integer
static void GcdPair(int [,]arr,
                    int k)
{
  // Initialize variables
  int lo = 0, hi = arr.Length - 1, mid;
  int []ans = {-1, 0};
 
  // Iterate until low less
  // than equal to high
  while (lo <= hi)
  {
    // Calculate mid
    mid = lo + (hi - lo) / 2;
    if (GCD(arr[mid, 0],
            arr[mid, 1]) > k)
    {
      ans = GetRow(arr, mid);
      hi = mid - 1;
    }
 
    // Reducing the search space
    else
      lo = mid + 1;
  }
 
  // Print the answer
  if (ans[0] == -1)
    Console.Write("-1");
  else
    Console.Write("( " + ans[0] +
                  ", " + ans[1] + " )");
  return;
}
 
public static int[] GetRow(int[,] matrix, int row)
{
  var rowLength = matrix.GetLength(1);
  var rowVector = new int[rowLength];
 
  for (var i = 0; i < rowLength; i++)
    rowVector[i] = matrix[row, i];
 
  return rowVector;
}
   
// Driver Code
public static void Main(String[] args)
{
  // Given array and K
  int [,]arr = {{3, 6},
                {15, 30},
                {25, 75},
                {30, 120}};
  int K = 16;
 
  // Function Call
  GcdPair(arr, K);
}
}
 
// This code is contributed by Rajput-Ji
chevron_right

Output
( 25, 75 )


Time Complexity: O(log(N)2
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.





DSC Lead at Google Developer Clubs

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :