# Calculate GCD of all pairwise sum of given two Arrays

• Difficulty Level : Medium
• Last Updated : 04 May, 2022

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 ` `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

 ``

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 + B[j], A + B[j], . . ., A[N-1] + B[j]) = GCD(A+B[j], A-A, A-A, . . ., A[N]-A).
The term GCD(A-A, A-A, . . ., A[N]-A) is common for all j from 0 to M-1 (say this is X)
• This leaves us with only the elements of type (A + 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 (say X).
• Then iterate through i = 1 to M-1 and calculate GCD of all pairs of A +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 ` `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+b[j], a[i]+b[j])` `    ``// =gcd(a+b[j], a[i]-a)` `    ``for` `(``int` `i = 1; i < N; i++) {` `        ``ans = gcd(ans, a[i] - a);` `    ``}`   `    ``// Calculating the gcd of the remaining` `    ``// elements of the type (a+b[j])` `    ``for` `(``int` `i = 0; i < M; i++) {` `        ``ans = gcd(ans, a + 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+b[j], a[i]+b[j])` `    ``// =gcd(a+b[j], a[i]-a)` `    ``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+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+b[j], a[i]+b[j])` `    ``# =gcd(a+b[j], a[i]-a)` `    ``for` `i ``in` `range``(``1``, N):` `        ``ans ``=` `gcd(ans, a[i] ``-` `a[``0``])` `        `  `    ``# Calculating the gcd of the remaining` `    ``# elements of the type (a+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+b[j], a[i]+b[j])` `    ``// =gcd(a+b[j], a[i]-a)` `    ``for` `(``int` `i = 1; i < N; i++) {` `      ``ans = gcd(ans, a[i] - a);` `    ``}`   `    ``// Calculating the gcd of the remaining` `    ``// elements of the type (a+b[j])` `    ``for` `(``int` `i = 0; i < M; i++) {` `      ``ans = gcd(ans, a + 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

 ``

Output

`2`

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :