Calculate GCD of all pairwise sum of given two Arrays
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 <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>
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>
Time Complexity : O(N*logN + M*logM)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read