📌  相关文章
📜  从 GCD 为 K 的两个给定数组生成 N 长序列

📅  最后修改于: 2021-10-26 05:28:47             🧑  作者: Mango

给定两个大小为N 的数组A[]B[] ,任务是生成长度为N的序列,其中包含来自两个数组的元素,使得生成的序列的 GCD 为K 。如果无法生成这样的序列,则打印“-1”

例子:

朴素方法:解决问题的最简单方法是使用递归。递归检查给定条件的所有可能组合。
请按照以下步骤解决问题:

  • 定义一个函数来递归生成所有可能的组合并执行以下步骤:
    • 基本条件是当前组合的长度等于N时,检查当前组合的GCD是否等于K。
    • 如果 GCD 等于K ,则打印组合并返回True 。否则,返回False
    • 将数组A[]中的一个元素添加到组合中并继续进行。
    • 在递归调用后删除添加的元素。
    • 将数组B[]中的一个元素添加到组合中并继续进行。
    • 在递归调用后删除添加的元素。
  • 如果任何组合的 GCD 不等于K ,则打印-1。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate
// GCD of two integers
int GCD(int a, int b)
{
    if (!b)
        return a;
    return GCD(b, a % b);
}
 
// Function to calculate
// GCD of a given array
int GCDArr(vector a)
{
    int ans = a[0];
    for (int i:a)
        ans = GCD(ans, i);
    return ans;
}
 
// Utility function to check for
// all the possible combinations
bool findSubseqUtil(vector  a,vector  b,
                    vector  &ans,int k,int i)
{
 
    // If an N-length sequence
    // is obtained
    if (ans.size() == a.size())
    {
 
        // If GCD of the sequence is K
        if (GCDArr(ans) == k)
        {
           cout << "[";
           int m = ans.size();
           for(int i = 0; i < m - 1; i++)
             cout << ans[i] << ", ";
           cout << ans[m - 1] << "]";
            return true;
          }
       
        // Otherwise
        else
            return false;
      }
 
    // Add an element from the first array
    ans.push_back(a[i]);
 
    // Recursively proceed further
    bool temp = findSubseqUtil(a, b, ans, k, i + 1);
 
    // If combination satisfies
    // the necessary condition
    if (temp)
        return true;
 
    // Remove the element
    // from the combination
    ans.pop_back();
 
    // Add an element from the second array
    ans.push_back(b[i]);
 
    // Recursive proceed further
    temp = findSubseqUtil(a, b, ans, k, i + 1);
 
    // If combination satisfies
    // the necessary condition
    if (temp)
        return true;
 
    // Remove the element
    // from the combination
    ans.pop_back();
    return false;
}
 
// Function to check all the
// possible combinations
void findSubseq(vector A, vector  B,
                int K, int i)
{
 
    // Stores the subsequence
    vector  ans;
 
    findSubseqUtil(A, B, ans, K, i);
 
    // If GCD is not equal to K
    // for any combination
    if (!ans.size())
        cout << -1;
}
 
// Driver Code
int main()
{
 
  // Given arrays
  vector A = {5, 3, 6, 2, 9};
  vector  B = {21, 7, 14, 12, 28};
 
  // Given value of K
  int K = 3;
 
  // Function call to generate
  // the required subsequence
  findSubseq(A, B, K, 0);
 
  return 0;
}
 
// This code is contributed by mohit kumar 29.


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
class GFG
{
 
  // Function to calculate
  // GCD of two integers
  static int GCD(int a, int b)
  {
    if (b < 1)
      return a;
    return GCD(b, a % b);
  }
 
  // Function to calculate
  // GCD of a given array
  static int GCDArr(ArrayList a)
  {
    int ans = a.get(0);
    for(int i : a) ans = GCD(ans, i);
    return ans;
  }
 
  // Utility function to check for
  // all the possible combinations
  static boolean findSubseqUtil(ArrayList a, ArrayList b,
                                ArrayList ans, int k, int i)
  {
 
    // If an N-length sequence
    // is obtained
    if (ans.size() == a.size()) {
 
      // If GCD of the sequence is K
      if (GCDArr(ans) == k) {
        System.out.print("[");
        int m = ans.size();
        for (int j = 0; j < m - 1; j++)
          System.out.print(ans.get(j) + ", ");
        System.out.print(ans.get(m-1) + "]");
        return true;
      }
 
      // Otherwise
      else
        return false;
    }
 
    // Add an element from the first array
    ans.add(a.get(i));
 
    // Recursively proceed further
    boolean temp = findSubseqUtil(a, b, ans, k, i + 1);
 
    // If combination satisfies
    // the necessary condition
    if (temp)
      return true;
 
    // Remove the element
    // from the combination
    ans.remove(ans.size() - 1);
 
    // Add an element from the second array
    ans.add(b.get(i));
 
    // Recursive proceed further
    temp = findSubseqUtil(a, b, ans, k, i + 1);
 
    // If combination satisfies
    // the necessary condition
    if (temp)
      return true;
 
    // Remove the element
    // from the combination
    ans.remove(ans.size() - 1);
    return false;
  }
 
  // Function to check all the
  // possible combinations
  static void findSubseq(ArrayList A, ArrayList B, int K,
                         int i)
  {
 
    // Stores the subsequence
    ArrayList ans = new ArrayList();
 
    findSubseqUtil(A, B, ans, K, i);
 
    // If GCD is not equal to K
    // for any combination
    if (ans.size() < 1)
      System.out.println(-1);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    // Given arrays
    ArrayList A = new ArrayList<>();
    A.add(5);
    A.add(3);
    A.add(6);
    A.add(2);
    A.add(9);
 
    ArrayList B = new ArrayList();
    B.add(21);
    B.add(7);
    B.add(14);
    B.add(12);
    B.add(28);
 
    // Given value of K
    int K = 3;
 
    // Function call to generate
    // the required subsequence
    findSubseq(A, B, K, 0);
  }
}
 
// This code is contributed by sanjoy_62.


Python3
# Python3 program for the above approach
 
# Function to calculate
# GCD of two integers
 
 
def GCD(a, b):
    if not b:
        return a
    return GCD(b, a % b)
 
# Function to calculate
# GCD of a given array
 
 
def GCDArr(a):
    ans = a[0]
    for i in a:
        ans = GCD(ans, i)
    return ans
 
# Utility function to check for
# all the possible combinations
 
 
def findSubseqUtil(a, b, ans, k, i):
 
    # If an N-length sequence
    # is obtained
    if len(ans) == len(a):
 
        # If GCD of the sequence is K
        if GCDArr(ans) == k:
            print(ans)
            return True
 
        # Otherwise
        else:
            return False
 
    # Add an element from the first array
    ans.append(a[i])
 
    # Recursively proceed further
    temp = findSubseqUtil(a, b, ans, k, i+1)
 
    # If combination satisfies
    # the necessary condition
    if temp == True:
        return True
 
    # Remove the element
    # from the combination
    ans.pop()
 
    # Add an element from the second array
    ans.append(b[i])
 
    # Recursive proceed further
    temp = findSubseqUtil(a, b, ans, k, i+1)
 
    # If combination satisfies
    # the necessary condition
    if temp == True:
        return True
 
    # Remove the element
    # from the combination
    ans.pop()
 
# Function to check all the
# possible combinations
 
 
def findSubseq(A, B, K, i):
 
    # Stores the subsequence
    ans = []
 
    findSubseqUtil(A, B, ans, K, i)
 
    # If GCD is not equal to K
    # for any combination
    if not ans:
        print(-1)
 
# Driver Code
 
 
# Given arrays
A = [5, 3, 6, 2, 9]
B = [21, 7, 14, 12, 28]
 
# Given value of K
K = 3
 
# Function call to generate
# the required subsequence
ans = findSubseq(A, B, K, 0)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to calculate
  // GCD of two integers
  static int GCD(int a, int b)
  {
    if (b < 1)
      return a;
    return GCD(b, a % b);
  }
 
  // Function to calculate
  // GCD of a given array
  static int GCDArr(List a)
  {
    int ans = a[0];
    foreach(int i in a) ans = GCD(ans, i);
    return ans;
  }
 
  // Utility function to check for
  // all the possible combinations
  static bool findSubseqUtil(List a, List b,
                             List ans, int k, int i)
  {
 
    // If an N-length sequence
    // is obtained
    if (ans.Count == a.Count) {
 
      // If GCD of the sequence is K
      if (GCDArr(ans) == k) {
        Console.Write("[");
        int m = ans.Count;
        for (int j = 0; j < m - 1; j++)
          Console.Write(ans[j] + ", ");
        Console.Write(ans[m - 1] + "]");
        return true;
      }
 
      // Otherwise
      else
        return false;
    }
 
    // Add an element from the first array
    ans.Add(a[i]);
 
    // Recursively proceed further
    bool temp = findSubseqUtil(a, b, ans, k, i + 1);
 
    // If combination satisfies
    // the necessary condition
    if (temp)
      return true;
 
    // Remove the element
    // from the combination
    ans.RemoveAt(ans.Count - 1);
 
    // Add an element from the second array
    ans.Add(b[i]);
 
    // Recursive proceed further
    temp = findSubseqUtil(a, b, ans, k, i + 1);
 
    // If combination satisfies
    // the necessary condition
    if (temp)
      return true;
 
    // Remove the element
    // from the combination
    ans.RemoveAt(ans.Count - 1);
    return false;
  }
 
  // Function to check all the
  // possible combinations
  static void findSubseq(List A, List B, int K,
                         int i)
  {
 
    // Stores the subsequence
    List ans = new List();
 
    findSubseqUtil(A, B, ans, K, i);
 
    // If GCD is not equal to K
    // for any combination
    if (ans.Count < 1)
      Console.WriteLine(-1);
  }
 
  // Driver Code
  public static void Main()
  {
 
    // Given arrays
    List A = new List{ 5, 3, 6, 2, 9 };
    List B = new List{ 21, 7, 14, 12, 28 };
 
    // Given value of K
    int K = 3;
 
    // Function call to generate
    // the required subsequence
    findSubseq(A, B, K, 0);
  }
}
 
// This code is contributed by ukasp.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
int GCD(int a, int b)
{
    if (b == 0)
        return a;
         
    return GCD(b, a % b);
}
 
// Function to calculate
// GCD of given array
int GCDArr(vector a)
{
    int ans = a[0];
    for(auto val : a)
    {
        ans = GCD(ans, val);
    }
    return ans;
}
 
// Utility function to check for
// all the combinations
bool findSubseqUtil(int a[], int b[], vector ans,
                    int k, int i, int N)
{
 
    // If a sequence of size N
    // is obtained
    if (ans.size() == N)
    {
         
        // If gcd of current
        // combination is K
        if (GCDArr(ans) == k)
        {
            for(auto val : ans)
                cout << val << " ";
                 
            return true;
        }
        else
        {
            return false;
        }
    }
     
    // If current element from
    // first array is divisible by K
    if (a[i] % k == 0)
    {
        ans.push_back(a[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.pop_back();
    }
 
    // If current element from
    // second array is divisible by K
    if (b[i] % k == 0)
    {
        ans.push_back(b[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.pop_back();
    }
    return false;
}
 
// Function to check for all
// possible combinations
void findSubseq(int A[], int B[], int K,
                int i, int N)
{
 
    // Stores the subsequence
    vector ans;
 
    bool ret = findSubseqUtil(A, B, ans,
                              K, i, N);
 
    // If GCD of any sequence
    // is not equal to K
    if (ret == false)
        cout << -1 << "\n";
}
 
// Driver Code
int main()
{
     
    // Given arrays
    int A[] = { 5, 3, 6, 2, 9 };
    int B[] = { 21, 7, 14, 12, 28 };
 
    // size of the array
    int N = sizeof(A) / sizeof(A[0]);
 
    // Given value of K
    int K = 3;
 
    // Function call to generate a
    // subsequence whose GCD is K
    findSubseq(A, B, K, 0, N);
 
    return 0;
}
 
// This code is contributed by Kingash


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
static int GCD(int a, int b)
{
    if (b == 0)
        return a;
         
    return GCD(b, a % b);
}
 
// Function to calculate
// GCD of given array
static int GCDArr(ArrayList a)
{
    int ans = a.get(0);
    for(int val : a)
    {
        ans = GCD(ans, val);
    }
    return ans;
}
 
// Utility function to check for
// all the combinations
static boolean findSubseqUtil(int a[], int b[],
                              ArrayList ans,
                              int k, int i)
{
     
    // If a sequence of size N
    // is obtained
    if (ans.size() == a.length)
    {
         
        // If gcd of current
        // combination is K
        if (GCDArr(ans) == k)
        {
            System.out.println(ans);
            return true;
        }
        else
        {
            return false;
        }
    }
     
    // If current element from
    // first array is divisible by K
    if (a[i] % k == 0)
    {
        ans.add(a[i]);
 
        // Recursively proceed further
        boolean temp = findSubseqUtil(a, b, ans,
                                      k, i + 1);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.remove(ans.size() - 1);
    }
 
    // If current element from
    // second array is divisible by K
    if (b[i] % k == 0)
    {
        ans.add(b[i]);
 
        // Recursively proceed further
        boolean temp = findSubseqUtil(a, b, ans,
                                      k, i + 1);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.remove(ans.size() - 1);
    }
    return false;
}
 
// Function to check for all
// possible combinations
static void findSubseq(int A[], int B[],
                       int K, int i)
{
     
    // Stores the subsequence
    ArrayList ans = new ArrayList<>();
 
    boolean ret = findSubseqUtil(A, B, ans, K, i);
 
    // If GCD of any sequence
    // is not equal to K
    if (ret == false)
        System.out.println(-1);
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Given arrays
    int A[] = { 5, 3, 6, 2, 9 };
    int B[] = { 21, 7, 14, 12, 28 };
 
    // Given value of K
    int K = 3;
 
    // Function call to generate a
    // subsequence whose GCD is K
    findSubseq(A, B, K, 0);
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Function to calculate
# GCD of two integers
 
 
def GCD(a, b):
    if not b:
        return a
    return GCD(b, a % b)
 
# Function to calculate
# GCD of given array
def GCDArr(a):
    ans = a[0]
    for i in a:
        ans = GCD(ans, i)
    return ans
 
# Utility function to check for
# all the combinations
def findSubseqUtil(a, b, ans, k, i):
 
    # If a sequence of size N
    # is obtained
    if len(ans) == len(a):
 
        # If gcd of current
        # combination is K
        if GCDArr(ans) == k:
            print(ans)
            return True
 
        else:
            return False
 
    # If current element from
    # first array is divisible by K
    if not a[i] % K:
        ans.append(a[i])
 
        # Recursively proceed further
        temp = findSubseqUtil(a, b, ans, k, i+1)
 
        # If current combination
        # satisfies given condition
        if temp == True:
            return True
 
        # Remove the element
        # from the combination
        ans.pop()
 
    # If current element from
    # second array is divisible by K
    if not b[i] % k:
 
        ans.append(b[i])
 
        # Recursively proceed further
        temp = findSubseqUtil(a, b, ans, k, i+1)
 
        # If current combination
        # satisfies given condition
        if temp == True:
            return True
 
        # Remove the element
        # from the combination
        ans.pop()
 
    return False
 
# Function to check for all
# possible combinations
def findSubseq(A, B, K, i):
 
    # Stores the subsequence
    ans = []
 
    findSubseqUtil(A, B, ans, K, i)
 
    # If GCD of any sequence
    # is not equal to K
    if not ans:
        print(-1)
 
# Driver Code
 
 
# Given arrays
A = [5, 3, 6, 2, 9]
B = [21, 7, 14, 12, 28]
 
# Given value of K
K = 3
 
# Function call to generate a
# subsequence whose GCD is K
ans = findSubseq(A, B, K, 0)


C#
// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG{
 
static int GCD(int a, int b)
{
    if (b == 0)
        return a;
         
    return GCD(b, a % b);
}
 
// Function to calculate
// GCD of given array
static int GCDArr(List a)
{
    int ans = a[0];
    foreach (int val in a)
    {
        ans = GCD(ans, val);
    }
    return ans;
}
 
// Utility function to check for
// all the combinations
static bool findSubseqUtil(int []a, int []b, List ans,
                    int k, int i, int N)
{
 
    // If a sequence of size N
    // is obtained
    if (ans.Count == N)
    {
         
        // If gcd of current
        // combination is K
        if (GCDArr(ans) == k)
        {
            foreach(int val in ans)
               Console.Write(val+" ");
                 
            return true;
        }
        else
        {
            return false;
        }
    }
     
    // If current element from
    // first array is divisible by K
    if (a[i] % k == 0)
    {
        ans.Add(a[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.RemoveAt(ans.Count - 1);
    }
 
    // If current element from
    // second array is divisible by K
    if (b[i] % k == 0)
    {
        ans.Add(b[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.RemoveAt(ans.Count - 1);
    }
    return false;
}
 
// Function to check for all
// possible combinations
static void findSubseq(int []A, int []B, int K,
                int i, int N)
{
 
    // Stores the subsequence
    List ans = new List();
 
    bool ret = findSubseqUtil(A, B, ans,
                              K, i, N);
 
    // If GCD of any sequence
    // is not equal to K
    if (ret == false)
        Console.Write(-1);
}
 
// Driver Code
public static void Main()
{
     
    // Given arrays
    int []A = { 5, 3, 6, 2, 9 };
    int []B = { 21, 7, 14, 12, 28 };
   
    // size of the array
    int N = A.Length;
   
    // Given value of K
    int K = 3;
   
    // Function call to generate a
    // subsequence whose GCD is K
    findSubseq(A, B, K, 0, N);
}
}
 
// This code is contributed by ipg2016107.


Javascript


输出:
[21, 3, 6, 12, 9]

时间复杂度: O(2 N * N * logN)
辅助空间: O(N)

高效方法:对上述方法进行优化,请按照以下步骤解决问题:

  • 序列的GCD将等于K,只有当所有存在于序列中的元素是用K整除。
  • 同时遍历数组并执行以下步骤:
    • 检查数组A[] 中的当前元素是否可被K整除。如果发现是真的,则进行递归调用。否则,返回false。
    • 检查数组B[] 中的当前元素是否可被K整除。如果发现是真的,则进行递归调用。否则,返回false

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
int GCD(int a, int b)
{
    if (b == 0)
        return a;
         
    return GCD(b, a % b);
}
 
// Function to calculate
// GCD of given array
int GCDArr(vector a)
{
    int ans = a[0];
    for(auto val : a)
    {
        ans = GCD(ans, val);
    }
    return ans;
}
 
// Utility function to check for
// all the combinations
bool findSubseqUtil(int a[], int b[], vector ans,
                    int k, int i, int N)
{
 
    // If a sequence of size N
    // is obtained
    if (ans.size() == N)
    {
         
        // If gcd of current
        // combination is K
        if (GCDArr(ans) == k)
        {
            for(auto val : ans)
                cout << val << " ";
                 
            return true;
        }
        else
        {
            return false;
        }
    }
     
    // If current element from
    // first array is divisible by K
    if (a[i] % k == 0)
    {
        ans.push_back(a[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.pop_back();
    }
 
    // If current element from
    // second array is divisible by K
    if (b[i] % k == 0)
    {
        ans.push_back(b[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.pop_back();
    }
    return false;
}
 
// Function to check for all
// possible combinations
void findSubseq(int A[], int B[], int K,
                int i, int N)
{
 
    // Stores the subsequence
    vector ans;
 
    bool ret = findSubseqUtil(A, B, ans,
                              K, i, N);
 
    // If GCD of any sequence
    // is not equal to K
    if (ret == false)
        cout << -1 << "\n";
}
 
// Driver Code
int main()
{
     
    // Given arrays
    int A[] = { 5, 3, 6, 2, 9 };
    int B[] = { 21, 7, 14, 12, 28 };
 
    // size of the array
    int N = sizeof(A) / sizeof(A[0]);
 
    // Given value of K
    int K = 3;
 
    // Function call to generate a
    // subsequence whose GCD is K
    findSubseq(A, B, K, 0, N);
 
    return 0;
}
 
// This code is contributed by Kingash

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
static int GCD(int a, int b)
{
    if (b == 0)
        return a;
         
    return GCD(b, a % b);
}
 
// Function to calculate
// GCD of given array
static int GCDArr(ArrayList a)
{
    int ans = a.get(0);
    for(int val : a)
    {
        ans = GCD(ans, val);
    }
    return ans;
}
 
// Utility function to check for
// all the combinations
static boolean findSubseqUtil(int a[], int b[],
                              ArrayList ans,
                              int k, int i)
{
     
    // If a sequence of size N
    // is obtained
    if (ans.size() == a.length)
    {
         
        // If gcd of current
        // combination is K
        if (GCDArr(ans) == k)
        {
            System.out.println(ans);
            return true;
        }
        else
        {
            return false;
        }
    }
     
    // If current element from
    // first array is divisible by K
    if (a[i] % k == 0)
    {
        ans.add(a[i]);
 
        // Recursively proceed further
        boolean temp = findSubseqUtil(a, b, ans,
                                      k, i + 1);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.remove(ans.size() - 1);
    }
 
    // If current element from
    // second array is divisible by K
    if (b[i] % k == 0)
    {
        ans.add(b[i]);
 
        // Recursively proceed further
        boolean temp = findSubseqUtil(a, b, ans,
                                      k, i + 1);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.remove(ans.size() - 1);
    }
    return false;
}
 
// Function to check for all
// possible combinations
static void findSubseq(int A[], int B[],
                       int K, int i)
{
     
    // Stores the subsequence
    ArrayList ans = new ArrayList<>();
 
    boolean ret = findSubseqUtil(A, B, ans, K, i);
 
    // If GCD of any sequence
    // is not equal to K
    if (ret == false)
        System.out.println(-1);
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Given arrays
    int A[] = { 5, 3, 6, 2, 9 };
    int B[] = { 21, 7, 14, 12, 28 };
 
    // Given value of K
    int K = 3;
 
    // Function call to generate a
    // subsequence whose GCD is K
    findSubseq(A, B, K, 0);
}
}
 
// This code is contributed by Kingash

蟒蛇3

# Python3 program for the above approach
 
# Function to calculate
# GCD of two integers
 
 
def GCD(a, b):
    if not b:
        return a
    return GCD(b, a % b)
 
# Function to calculate
# GCD of given array
def GCDArr(a):
    ans = a[0]
    for i in a:
        ans = GCD(ans, i)
    return ans
 
# Utility function to check for
# all the combinations
def findSubseqUtil(a, b, ans, k, i):
 
    # If a sequence of size N
    # is obtained
    if len(ans) == len(a):
 
        # If gcd of current
        # combination is K
        if GCDArr(ans) == k:
            print(ans)
            return True
 
        else:
            return False
 
    # If current element from
    # first array is divisible by K
    if not a[i] % K:
        ans.append(a[i])
 
        # Recursively proceed further
        temp = findSubseqUtil(a, b, ans, k, i+1)
 
        # If current combination
        # satisfies given condition
        if temp == True:
            return True
 
        # Remove the element
        # from the combination
        ans.pop()
 
    # If current element from
    # second array is divisible by K
    if not b[i] % k:
 
        ans.append(b[i])
 
        # Recursively proceed further
        temp = findSubseqUtil(a, b, ans, k, i+1)
 
        # If current combination
        # satisfies given condition
        if temp == True:
            return True
 
        # Remove the element
        # from the combination
        ans.pop()
 
    return False
 
# Function to check for all
# possible combinations
def findSubseq(A, B, K, i):
 
    # Stores the subsequence
    ans = []
 
    findSubseqUtil(A, B, ans, K, i)
 
    # If GCD of any sequence
    # is not equal to K
    if not ans:
        print(-1)
 
# Driver Code
 
 
# Given arrays
A = [5, 3, 6, 2, 9]
B = [21, 7, 14, 12, 28]
 
# Given value of K
K = 3
 
# Function call to generate a
# subsequence whose GCD is K
ans = findSubseq(A, B, K, 0)

C#

// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG{
 
static int GCD(int a, int b)
{
    if (b == 0)
        return a;
         
    return GCD(b, a % b);
}
 
// Function to calculate
// GCD of given array
static int GCDArr(List a)
{
    int ans = a[0];
    foreach (int val in a)
    {
        ans = GCD(ans, val);
    }
    return ans;
}
 
// Utility function to check for
// all the combinations
static bool findSubseqUtil(int []a, int []b, List ans,
                    int k, int i, int N)
{
 
    // If a sequence of size N
    // is obtained
    if (ans.Count == N)
    {
         
        // If gcd of current
        // combination is K
        if (GCDArr(ans) == k)
        {
            foreach(int val in ans)
               Console.Write(val+" ");
                 
            return true;
        }
        else
        {
            return false;
        }
    }
     
    // If current element from
    // first array is divisible by K
    if (a[i] % k == 0)
    {
        ans.Add(a[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.RemoveAt(ans.Count - 1);
    }
 
    // If current element from
    // second array is divisible by K
    if (b[i] % k == 0)
    {
        ans.Add(b[i]);
 
        // Recursively proceed further
        bool temp = findSubseqUtil(a, b, ans, k,
                                   i + 1, N);
 
        // If current combination
        // satisfies given condition
        if (temp == true)
            return true;
 
        // Remove the element
        // from the combination
        ans.RemoveAt(ans.Count - 1);
    }
    return false;
}
 
// Function to check for all
// possible combinations
static void findSubseq(int []A, int []B, int K,
                int i, int N)
{
 
    // Stores the subsequence
    List ans = new List();
 
    bool ret = findSubseqUtil(A, B, ans,
                              K, i, N);
 
    // If GCD of any sequence
    // is not equal to K
    if (ret == false)
        Console.Write(-1);
}
 
// Driver Code
public static void Main()
{
     
    // Given arrays
    int []A = { 5, 3, 6, 2, 9 };
    int []B = { 21, 7, 14, 12, 28 };
   
    // size of the array
    int N = A.Length;
   
    // Given value of K
    int K = 3;
   
    // Function call to generate a
    // subsequence whose GCD is K
    findSubseq(A, B, K, 0, N);
}
}
 
// This code is contributed by ipg2016107.

Javascript


输出:
[21, 3, 6, 12, 9]

时间复杂度: O(2 N * N * logN)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程