Find GCD of Array after subtracting given value for M queries
Last Updated :
19 Jan, 2023
Given an array, arr[] of size N, Given M queries and each query consisting of a number X, the task is to subtract X from every element of arr[] for each query and print the Greatest Common Divisor of all elements of arr[].
Examples:
Input: arr[] = {9, 13, 17, 25}, Q[] = {1, 3, 5, 9}
Output: 4 2 4 4
Explanation: First Query: GCD(9 - 1, 13 -1, 17 - 1, 25 - 1) = GCD(8, 12, 16, 24) = 4
Second Query: GCD(9 - 3, 13 - 3, 17 - 3, 25 - 3) = GCD(6, 10, 14, 22) = 2
Third Query: GCD(9 - 5, 13 - 5, 17 - 5, 25 - 5) = GCD(4, 8, 12, 20) = 4
Fourth Query: GCD(9 - 9, 13 - 9, 17 - 9, 25 - 9) = GCD(0, 4, 8,, 16) = 4
Input: arr[] = {1 25 121 169}, Q[] = {1 2 7 23}
Output: 24 1 6 2
Naive approach: The basic way to solve the problem is as follows:
For each query Iterate through every element of arr[] and keep track of GCD.
Time Complexity: O(N * M * logD) where D is the maximum value of the array
Auxiliary Space: O(1)
Efficient Approach: The problem can be solved based on the following idea:
Property of Euclidean Algorithm for finding GCD can be used which is GCD(a, b) = GCD(a, b - a). For multiple numbers idea can be generalized as GCD(a, b, c, …) = GCD(a, b - a, c - a, …).
Follow the steps below to solve the problem:
- To calculate GCD(arr[0] - X, arr[1] - X, arr[2] - X, . . ., arr[N - 1] - X), subtract arr[0] - X from other Numbers.
- Then, GCD (arr[0] - X, arr[1] - X, arr[2] - X, . . ., arr[N - 1] - X) = GCD(arr[0] - X, arr[1] - arr[0], arr[2] - arr[0], . . ., arr[N - 1] - arr[0]).
- Find T = GCD( arr[1] - arr[0], arr[2] - arr[0], . . ., arr[N - 1] - arr[0]), then gcd for every query can be calculated to be GCD(arr[0] - X, T).
- For each query print the absolute of GCD(X, T) (print absolute since the answer can be negative after subtraction).
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to Calculate GCD for each query
vector<int> findGCDBySubtractingX(int arr[], int Q[],
int N, int M)
{
int T = 0;
vector<int> res;
// Find GCD of arr[1] - arr[0], arr[2] - arr[0],
// . . ., arr[N - 1] - arr[0]
for (int i = 1; i < N; i++) {
T = __gcd(T, arr[i] - arr[0]);
}
// Iterating for each of M Queries
for (int j = 0; j < M; j++) {
int X = Q[j];
// Finding GCD for each query with
// their absolute since subtraction
// can be negative
res.push_back(abs(__gcd(T, arr[0] - X)));
}
return res;
}
// Driver Code
int main()
{
// Input
int arr[] = { 9, 13, 17, 25 }, Q[] = { 1, 3, 5, 9 };
int N = sizeof(arr) / sizeof(arr[0]);
int M = sizeof(Q) / sizeof(Q[0]);
// Function Call
vector<int> ans = findGCDBySubtractingX(arr, Q, N, M);
for (int x : ans)
cout << x << " ";
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
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 for each query
public static List<Integer>
findGCDBySubtractingX(int[] arr, int[] Q, int N, int M)
{
int T = 0;
List<Integer> res = new ArrayList<>();
// Find GCD of arr[1] - arr[0], arr[2] - arr[0],
// . . ., arr[N - 1] - arr[0]
for (int i = 1; i < N; i++) {
T = gcd(T, arr[i] - arr[0]);
}
// Iterating for each of M Queries
for (int j = 0; j < M; j++) {
int X = Q[j];
// Finding GCD for each query with
// their absolute since subtraction
// can be negative
res.add(Math.abs(gcd(T, arr[0] - X)));
}
return res;
}
// Driver Code
public static void main(String[] args)
{
// Input
int[] arr = { 9, 13, 17, 25 };
int[] Q = { 1, 3, 5, 9 };
int N = arr.length;
int M = Q.length;
// Function Call
List<Integer> ans
= findGCDBySubtractingX(arr, Q, N, M);
for (int x : ans)
System.out.print(x + " ");
}
}
// This code is contributed by lokeshmvs21.
Python3
import math
def findGCDBySubtractingX(arr, q, n, m):
t = 0
res = []
# find the gcd of arr[1]-arr[0]
# .... arr[n-1]-arr[0]
for i in range(1, n):
t = math.gcd(t, arr[i]-arr[0])
# Iterating for each of m queries
for j in range(m):
x = q[j]
# finding the gcd for each query with
# their absolute since subtraction
# can be negative
res.append(abs(math.gcd(t, arr[0]-x)))
return res
arr = [9, 13, 17, 25]
q = [1, 3, 5, 9]
n = len(arr)
m = len(q)
ans = findGCDBySubtractingX(arr, q, n, m)
for x in ans:
print(x, end=" ")
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
public class GFG {
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to Calculate GCD for each query
public static List<int>
findGCDBySubtractingX(int[] arr, int[] Q, int N, int M)
{
int T = 0;
List<int> res = new List<int>();
// Find GCD of arr[1] - arr[0], arr[2] - arr[0],
// . . ., arr[N - 1] - arr[0]
for (int i = 1; i < N; i++) {
T = gcd(T, arr[i] - arr[0]);
}
// Iterating for each of M Queries
for (int j = 0; j < M; j++) {
int X = Q[j];
// Finding GCD for each query with
// their absolute since subtraction
// can be negative
res.Add(Math.Abs(gcd(T, arr[0] - X)));
}
return res;
}
static public void Main()
{
// Input
int[] arr = { 9, 13, 17, 25 };
int[] Q = { 1, 3, 5, 9 };
int N = arr.Length;
int M = Q.Length;
// Function Call
List<int> ans = findGCDBySubtractingX(arr, Q, N, M);
foreach(int x in ans) Console.Write(x + " ");
}
}
// This code is contributed by lokesh.
JavaScript
// JavaScript code to implement the approach
// function to find gcd
function __gcd(a, b)
{
if(b==0)
return a;
else
return __gcd(b, a%b);
}
// Function to Calculate GCD for each query
function findGCDBySubtractingX(arr, Q, N, M)
{
let T = 0;
let res=[];
// Find GCD of arr[1] - arr[0], arr[2] - arr[0],
// . . ., arr[N - 1] - arr[0]
for (let i = 1; i < N; i++) {
T = __gcd(T, arr[i] - arr[0]);
}
// Iterating for each of M Queries
for (let j = 0; j < M; j++) {
let X = Q[j];
// Finding GCD for each query with
// their absolute since subtraction
// can be negative
res.push(Math.abs(__gcd(T, arr[0] - X)));
}
return res;
}
// Driver Code
// Input
let arr = [ 9, 13, 17, 25 ], Q = [ 1, 3, 5, 9 ];
let N = arr.length;
let M = Q.length;
// Function Call
let ans = findGCDBySubtractingX(arr, Q, N, M);
for (let x of ans)
console.log(x + " ");
// This code is contributed by poojaagarwal2.
Time Complexity: O(N * logD + M * logD) where D is the maximum element in the array
Auxiliary Space: O(1)
Related Articles:
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
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
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
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
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
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read