Open In App

Calculate GCD of all pairwise sum of given two Arrays

Last Updated : 04 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays A[] and B[] of size N and M calculate GCD of all pairwise sum of (A[i]+B[j]) 1<=i<=N and 1<=j<=M.

Examples: 

Input: A[] = {1, 7, 25, 55}, B[] = {1, 3, 5}
Output: 2
Explanation: The GCD of all pairwise sum of (A[i]+B[j]) is equals to 
GCD(1+1, 1+3, 1+5, 7+1, 7+3, 7+5, 25+1, 25+3, 25+5, 55+1, 55+3, 55+5)
GCD(2, 4, 6, 8, 10, 12, 26, 28, 30, 56, 58, 60) = 2

Input: A[] = {8, 16, 20}, B[] = {12, 24}
Output: 4 

 

Naive Approach: The simple approach of this problem is to calculate all pairwise sums and then calculate their GCD.

Below is the implementation of this approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate gcd
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Function to calculate the GCD
// of all pairwise sums
int calculateGCD(vector<int>& a,
                 vector<int>& b,
                 int N, int M)
{
    int ans = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
 
            // Pairwise sum of all elements
            int sum = a[i] + b[j];
 
            // Finding gcd of the elements
            ans = gcd(ans, sum);
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int N = 4, M = 3;
    // Initialization of the vector
    vector<int> A = { 1, 7, 25, 55 };
    vector<int> B = { 1, 3, 5 };
 
    // output
    cout << calculateGCD(A, B, N, M);
    return 0;
}


Java




// Java code to implement the approach
import java.util.*;
 
class GFG {
 
  // Function to calculate gcd
  static int gcd(int a, int b)
  {
    if (b == 0)
      return a;
    return gcd(b, a % b);
  }
 
  // Function to calculate the GCD
  // of all pairwise sums
  static int calculateGCD(int a[],
                          int b[],
                          int N, int M)
  {
    int ans = 0;
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < M; j++) {
 
        // Pairwise sum of all elements
        int sum = a[i] + b[j];
 
        // Finding gcd of the elements
        ans = gcd(ans, sum);
      }
    }
    return ans;
  }
 
  // Driver code
  public static void main (String[] args) {
    int N = 4, M = 3;
 
    // Initialization of the vector
    int A[] = { 1, 7, 25, 55 };
    int B[] = { 1, 3, 5 };
 
    // output
    System.out.print(calculateGCD(A, B, N, M));
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# Python code to implement the approach
# Function to calculate gcd
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)
   
# Function to calculate the GCD
# of all pairwise sums
def calculateGCD(a, b, N, M):
    ans = 0
    for i in range(N):
        for j in range(M):
           
            # Pairwise sum of all elements
            sum = a[i]+b[j]
             
            # Finding gcd of the elements
            ans = gcd(ans, sum)
    return ans
 
# Driver code
N = 4
M = 3
A = [1, 7, 25, 55]
B = [1, 3, 5]
print(calculateGCD(A, B, N, M))
 
'''This Code is contributed by Rajat Kumar'''


C#




// C# code to implement the approach
using System;
using System.Numerics;
using System.Collections.Generic;
 
public class GFG {
 
  // Function to calculate gcd
  static int gcd(int a, int b)
  {
    if (b == 0)
      return a;
    return gcd(b, a % b);
  }
 
  // Function to calculate the GCD
  // of all pairwise sums
  static int calculateGCD(int[] a, int[] b, int N, int M)
  {
    int ans = 0;
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < M; j++) {
 
        // Pairwise sum of all elements
        int sum = a[i] + b[j];
 
        // Finding gcd of the elements
        ans = gcd(ans, sum);
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int N = 4, M = 3;
     
    // Initialization of the vector
    int[] A = { 1, 7, 25, 55 };
    int[] B = { 1, 3, 5 };
 
    // output
    Console.WriteLine(calculateGCD(A, B, N, M));
  }
}
 
// This code is contributed by phasing17


Javascript




<script>
    // JavaScript code to implement the approach
 
    // Function to calculate gcd
    const gcd = (a, b) => {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
 
    // Function to calculate the GCD
    // of all pairwise sums
    const calculateGCD = (a, b, N, M) => {
        let ans = 0;
        for (let i = 0; i < N; i++) {
            for (let j = 0; j < M; j++) {
 
                // Pairwise sum of all elements
                let sum = a[i] + b[j];
 
                // Finding gcd of the elements
                ans = gcd(ans, sum);
            }
        }
        return ans;
    }
 
    // Driver code
 
    let N = 4, M = 3;
    // Initialization of the vector
    let A = [1, 7, 25, 55];
    let B = [1, 3, 5];
 
    // output
    document.write(calculateGCD(A, B, N, M));
 
// This code is contributed by rakeshsahni
 
</script>


Output

2

Time Complexity: O(N*M)
Auxiliary Space: O(N)

Efficient Approach: The problem can be solved efficiently based on the following mathematical observation:

Observation

  • By Euclidean algorithm it can be said that GCD( a, b) =  GCD(a-b, b) where(a>b) .   
  • Then for any j
    GCD(A[0] + B[j], A[1] + B[j], . . ., A[N-1] + B[j]) = GCD(A[0]+B[j], A[1]-A[0], A[2]-A[0], . . ., A[N]-A[0]). 
    The term GCD(A[1]-A[0], A[2]-A[0], . . ., A[N]-A[0]) is common for all j from 0 to M-1 (say this is X)
  • This leaves us with only the elements of type (A[0] + B[j]) for which will calculate their GCD and will get the desired GCD upon calculating their GCD with X

Follow the below steps to solve this problem: 

  • First sort both the arrays.
  • Then iterate through i = 1 to N-1 and calculate GCD of all pairs of A[i] -A[0] (say X).
  • Then iterate through i = 1 to M-1 and calculate GCD of all pairs of A[0] +B[i] (say Y).
  • Return the final answer which is GCD of (X and Y).

Below is the implementation of this approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function for calculating gcd
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Function to calculate the required GCD
int calculateGCD(vector<int>& a,
                 vector<int>& b, int N, int M)
{
    int ans = 0;
 
    // Sorting the arrays
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
 
    // Calculating the gcd of all the elements
    // of type (i, j) i>0 and j>=0
    // Using the property
    // gcd(a[0]+b[j], a[i]+b[j])
    // =gcd(a[0]+b[j], a[i]-a[0])
    for (int i = 1; i < N; i++) {
        ans = gcd(ans, a[i] - a[0]);
    }
 
    // Calculating the gcd of the remaining
    // elements of the type (a[0]+b[j])
    for (int i = 0; i < M; i++) {
        ans = gcd(ans, a[0] + b[i]);
    }
    return ans;
}
 
// Driver code
int main()
{
    int N = 4, M = 3;
    // Initialization of the array
    vector<int> A = { 1, 7, 25, 55 };
    vector<int> B = { 1, 3, 5 };
 
    // Function call
    cout << calculateGCD(A, B, N, M);
    return 0;
}


Java




// JAVA code to implement the above approach
import java.util.*;
class GFG {
  // Function to calculate gcd
  static int gcd(int a, int b)
  {
    if (b == 0)
      return a;
    return gcd(b, a % b);
  }
 
  // Function to calculate the GCD
  // of all pairwise sums
  static int calculateGCD(int a[],
                          int b[],
                          int N, int M)
  {
    int ans = 0;
 
    // Sorting the arrays
    Arrays.sort(a);
    Arrays.sort(b);
 
    // Calculating the gcd of all the elements
    // of type (i, j) i>0 and j>=0
    // Using the property
    // gcd(a[0]+b[j], a[i]+b[j])
    // =gcd(a[0]+b[j], a[i]-a[0])
    for (int i = 1; i < N; i++) {
      ans = gcd(ans, a[i] - a[0]);
    }
 
    // Calculating the gcd of the remaining
    // elements of the type (a[0]+b[j])
    for (int i = 0; i < M; i++) {
      ans = gcd(ans, a[0] + b[i]);
    }
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 4, M = 3;
 
    // Initialization of the vector
    int A[] = { 1, 7, 25, 55 };
    int B[] = { 1, 3, 5 };
 
    // output
    System.out.print(calculateGCD(A, B, N, M));
  }
}
 
// This code is contributed by sanjoy_62.


Python3




# Python3 code to implement the approach
 
# Function for calculating gcd
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)
 
# Function to calculate the required GCD
def calculateGCD(a, b, N, M):
    ans = 0
     
    # sorting the arrays
    a.sort()
    b.sort()
     
    # calculating the gcd of all the elements
    # of type (i, j) i>0 and j>=0
    # Using the property
    # gcd(a[0]+b[j], a[i]+b[j])
    # =gcd(a[0]+b[j], a[i]-a[0])
    for i in range(1, N):
        ans = gcd(ans, a[i] - a[0])
         
    # Calculating the gcd of the remaining
    # elements of the type (a[0]+b[j])
    for i in range(M):
        ans = gcd(ans, a[0] + b[i])
    return ans
 
# Driver code
N, M = 4, 3
A = [1, 7, 25, 55]
B = [1, 3, 5]
 
# function all
print(calculateGCD(A, B, N, M))
 
# This code is contributed by phasing17.


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to calculate gcd
  static int gcd(int a, int b)
  {
    if (b == 0)
      return a;
    return gcd(b, a % b);
  }
 
  // Function to calculate the GCD
  // of all pairwise sums
  static int calculateGCD(int[] a,
                          int[] b,
                          int N, int M)
  {
    int ans = 0;
 
    // Sorting the arrays
    Array.Sort(a);
    Array.Sort(b);
 
    // Calculating the gcd of all the elements
    // of type (i, j) i>0 and j>=0
    // Using the property
    // gcd(a[0]+b[j], a[i]+b[j])
    // =gcd(a[0]+b[j], a[i]-a[0])
    for (int i = 1; i < N; i++) {
      ans = gcd(ans, a[i] - a[0]);
    }
 
    // Calculating the gcd of the remaining
    // elements of the type (a[0]+b[j])
    for (int i = 0; i < M; i++) {
      ans = gcd(ans, a[0] + b[i]);
    }
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 4, M = 3;
 
    // Initialization of the vector
    int[] A = { 1, 7, 25, 55 };
    int[] B = { 1, 3, 5 };
 
    // output
    Console.Write(calculateGCD(A, B, N, M));
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
// JavaScript code to implement the approach
 
// Function for calculating gcd
function gcd(a, b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
// Function to calculate the required GCD
function calculateGCD(a, b, N, M)
{
    var ans = 0;
     
    // sorting the arrays
    a.sort()
    b.sort()
     
    // calculating the gcd of all the elements
    // of type (i, j) i>0 and j>=0
    // Using the property
    // gcd(a[0]+b[j], a[i]+b[j])
    // =gcd(a[0]+b[j], a[i]-a[0])
    for (var i = 1; i < N; i++)
        ans = gcd(ans, a[i] - a[0]);
         
    // Calculating the gcd of the remaining
    // elements of the type (a[0]+b[j])
    for (var i = 0; i < M; i++)
        ans = gcd(ans, a[0] + b[i]);
    return ans;
}
 
// Driver code
var N = 4;
var M =  3;
var A = [1, 7, 25, 55];
var B = [1, 3, 5];
 
// function all
document.write(calculateGCD(A, B, N, M))
 
// This code is contributed by phasing17.
</script>


Output

2

Time Complexity : O(N*logN + M*logM) 
Auxiliary Space: O(1)



Similar Reads

XOR of all possible pairwise sum from two given Arrays
Given two arrays A[] and B[] of equal length, the task is to find the Bitwise XOR of the pairwise sum of the given two arrays. Examples: Input: A[] = {1, 2}, B[] = {3, 4} Output: 2 Explanation: Sum of all possible pairs are {4(1 + 3), 5(1 + 4), 5(2 + 3), 6(2 + 4)} XOR of all the pair sums = 4 ^ 5 ^ 5 ^ 6 = 2 Input: A[] = {4, 6, 0, 0, 3, 3}, B[] = {
16 min read
Kth largest pairwise product possible from given two Arrays
Given two arrays arr[] and brr[] containing integers. The task is to find the Kth largest product of a pair (arr[i], brr[j]). Examples: Input: arr[] = {1, -2, 3}, brr[] = {3, -4, 0}, K = 3Output: 3Explanation: All product combinations in descending order are : [9, 8, 3, 0, 0, 0, -4, -6, -12] and 3rd largest element is 3. Input: arr[] = {-1, -5, -3}
14 min read
Maximize sum of pairwise products generated from the given Arrays
Given three arrays arr1[], arr2[] and arr3[] of length N1, N2, and N3 respectively, the task is to find the maximum sum possible by adding the products of pairs taken from different arrays. Note: Each array element can be a part of a single pair. Examples: Input: arr1[] = {3, 5}, arr2[] = {2, 1}, arr3[] = {4, 3, 5}Output : 43ExplanationAfter sortin
11 min read
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: (2
7 min read
Calculate the Sum of GCD over all subarrays
Given an array of integers, the task is to calculate the sum of GCD of all the subarrays of an array. GCD of an array is defined as the GCD of all the elements present in it. More formally, [Tex]GCD(A[n]) = GCD(A_1, A_2, A_3....A_n) [/Tex]. Summation of all the GCDs can be defined as [Tex]\sum_{i=1}^{n}\sum_{j=i}^{n} GCD(A_{ij}) [/Tex]where [Tex]A_
19 min read
Count all possible values of K less than Y such that GCD(X, Y) = GCD(X+K, Y)
Given two integers X and Y, the task is to find the number of integers, K, such that gcd(X, Y) is equal to gcd(X+K, Y), where 0 &lt; K &lt;Y. Examples: Input: X = 3, Y = 15Output: 4Explanation: All possible values of K are {0, 3, 6, 9} for which GCD(X, Y) = GCD(X + K, Y). Input: X = 2, Y = 12Output: 2Explanation: All possible values of K are {0, 8}
8 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Smallest subsequence having GCD equal to GCD of given array
Given an array arr[] of size N, the task is to find the smallest subsequence of the given array whose GCD of the subsequence is equal to the GCD of the given array. If more than one such subsequence exists, then print anyone of them. Examples: Input: arr[] = {4, 6, 12}Output: 4 6Explanation: Smallest subsequence having gcd equal to gcd of the given
7 min read
Generate an N-length sequence from two given arrays whose GCD is K
Given two arrays A[] and B[], both of size N, the task is to generate a sequence of length N comprising elements from the two arrays such that the GCD of the generated sequence is K. If it is not possible to generate such a sequence, then print "-1". Examples: Input: A[] = {5, 3, 6, 2, 9}, B[] = {21, 7, 14, 12, 28}, K = 3Output: 21, 3, 6, 12, 9Expl
20 min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Practice Tags :