📜  在 GCD 超过 K 的所有给定对中,具有最小 GCD 的整数对

📅  最后修改于: 2021-09-03 14:37:15             🧑  作者: Mango

给定一个数组arr[][]包含按 GCD 递增顺序的整数对和整数K ,任务是找到一对整数,其 GCD 至少为K并且也是所有可能的 GCD 中超过K的最小的整数。如果不存在这样的对,则打印-1
例子:

朴素的方法:最简单的方法是迭代给定数组的所有对,并检查每一对的 GCD 是否超过K 。从所有这些对中,打印具有最小GCD的对。

时间复杂度: O(N * log(N))
辅助空间: O(1)

有效的方法:这个想法是观察数组元素按其对的 GCD 值的递增顺序排序,因此使用二分搜索。请按照以下步骤解决问题:

  • 计算搜索空间的中值并检查arr[mid] > K 的GCD。
  • 如果超过K ,则更新答案并将搜索空间的上限值减少到mid – 1
  • 如果arr[mid]的 GCD ≤ K ,则将搜索空间的下限值增加到mid + 1
  • 继续上述过程,直到下限值小于或等于上限值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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 > arr, int k)
{
    // Initialize variables
    int lo = 0, hi = arr.size() - 1, mid;
    pair ans;
    ans = make_pair(-1, 0);
 
    // Iterate 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 > arr = { { 3, 6 },
                                    { 15, 30 },
                                    { 25, 75 },
                                    { 30, 120 } };
    int K = 16;
 
    // Function Call
    GcdPair(arr, K);
 
    return 0;
}


Java
// 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


Python3
# 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 print the 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]
 
    # 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 (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


C#
// 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


Javascript


输出
( 25, 75 )

时间复杂度: O(log(N) 2 )
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live