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

📅  最后修改于: 2021-04-29 04:59:48             🧑  作者: Mango

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

天真的方法:最简单的方法是遍历给定数组的所有对,并检查每对,如果其GCD超过K。从所有这样的对中,打印GCD最小的对。

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

高效方法:想法是观察数组元素按其对的GCD值的升序排列,因此请使用二进制搜索。请按照以下步骤解决问题:

  • 计算搜索空间的中间值,并检查arr [mid]> K的GCD。
  • 如果超过K ,则更新答案并将搜索空间的上限值减小到中间– 1
  • 如果arr [mid]≤K的GCD,则将搜索空间的下限值增加到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);
 
    // 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 > 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 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


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)