Given an array a[0 . . . n-1]. We should be able to efficiently find the GCD from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1.

Example :

Input : a[] = {2, 3, 60, 90, 50}; Index Ranges : {1, 3}, {2, 4}, {0, 2} Output: GCDs of given ranges are 3, 10, 1

**Method 1 (Simple)**

A simple solution is to run a loop from qs to qe and find GCD in given range. This solution takes O(n) time in worst case.

**Method 2 (2D Array)**

Another solution is to create a 2D array where an entry [i, j] stores the GCD in range arr[i..j]. GCD of a given range can now be calculated in O(1) time, but preprocessing takes O(n^2) time. Also, this approach needs O(n^2) extra space which may become huge for large input arrays.

**Method 3 (Segment Tree) **

Prerequisites : Segment Tree Set 1, Segment Tree Set 2

Segment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for GCD query is O(Logn). The extra space required is O(n) to store the segment tree.

**Representation of Segment trees**

- Leaf Nodes are the elements of the input array.
- Each internal node represents GCD of all leaves under it.

Array representation of tree is used to represent Segment Trees i.e., for each node at index i,

- Left child is at index 2*i+1
- Right child at 2*i+2 and the parent is at floor((i-1)/2).

**Construction of Segment Tree from given array**

- Begin with a segment arr[0 . . . n-1] and keep dividing into two halves. Every time we divide the current segment into two halves (if it has not yet become a segment of length 1), then call the same procedure on both halves, and for each such segment, we store the GCD value in a segment tree node.
- All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree (every node has 0 or two children) because we always divide segments in two halves at every level.
- Since the constructed tree is always full binary tree with n leaves, there will be n-1 internal nodes. So total number of nodes will be 2*n – 1.
- Height of the segment tree will be &lceillog
_{2}n&rceil. Since the tree is represented using array and relation between parent and child indexes must be maintained, size of memory allocated for segment tree will be 2*2^{⌈log2n⌉}– 1

**Query for GCD of given range**

/ qs --> query start index, qe --> query end index int GCD(node, qs, qe) { if range of node is within qs and qe return value in node else if range of node is completely outside qs and qe return INFINITE else return GCD( GCD(node's left child, qs, qe), GCD(node's right child, qs, qe) ) }

Below is Implementation of this method.

## C++

// C++ Program to find GCD of a number in a given Range // using segment Trees #include <bits/stdc++.h> using namespace std; // To store segment tree int *st; // Function to find gcd of 2 numbers. int gcd(int a, int b) { if (a < b) swap(a, b); if (b==0) return a; return gcd(b, a%b); } /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int findGcd(int ss, int se, int qs, int qe, int si) { if (ss>qe || se < qs) return 0; if (qs<=ss && qe>=se) return st[si]; int mid = ss+(se-ss)/2; return gcd(findGcd(ss, mid, qs, qe, si*2+1), findGcd(mid+1, se, qs, qe, si*2+2)); } //Finding The gcd of given Range int findRangeGcd(int ss, int se, int arr[],int n) { if (ss<0 || se > n-1 || ss>se) { cout << "Invalid Arguments" << "\n"; return -1; } return findGcd(0, n-1, ss, se, 0); } // A recursive function that constructs Segment Tree for // array[ss..se]. si is index of current node in segment // tree st int constructST(int arr[], int ss, int se, int si) { if (ss==se) { st[si] = arr[ss]; return st[si]; } int mid = ss+(se-ss)/2; st[si] = gcd(constructST(arr, ss, mid, si*2+1), constructST(arr, mid+1, se, si*2+2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int *constructSegmentTree(int arr[], int n) { int height = (int)(ceil(log2(n))); int size = 2*(int)pow(2, height)-1; st = new int[size]; constructST(arr, 0, n-1, 0); return st; } // Driver program to test above functions int main() { int a[] = {2, 3, 6, 9, 5}; int n = sizeof(a)/sizeof(a[0]); // Build segment tree from given array constructSegmentTree(a, n); // Starting index of range. These indexes are 0 based. int l = 1; // Last index of range.These indexes are 0 based. int r = 3; cout << "GCD of the given range is:"; cout << findRangeGcd(l, r, a, n) << "\n"; return 0; }

## Java

// Java Program to find GCD of a number in a given Range // using segment Trees import java.io.*; public class Main { private static int[] st; // Array to store segment tree /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ public static int[] constructSegmentTree(int[] arr) { int height = (int)Math.ceil(Math.log(arr.length)/Math.log(2)); int size = 2*(int)Math.pow(2, height)-1; st = new int[size]; constructST(arr, 0, arr.length-1, 0); return st; } // A recursive function that constructs Segment // Tree for array[ss..se]. si is index of current // node in segment tree st public static int constructST(int[] arr, int ss, int se, int si) { if (ss==se) { st[si] = arr[ss]; return st[si]; } int mid = ss+(se-ss)/2; st[si] = gcd(constructST(arr, ss, mid, si*2+1), constructST(arr, mid+1, se, si*2+2)); return st[si]; } // Function to find gcd of 2 numbers. private static int gcd(int a, int b) { if (a < b) { // If b greater than a swap a and b int temp = b; b = a; a = temp; } if (b==0) return a; return gcd(b,a%b); } //Finding The gcd of given Range public static int findRangeGcd(int ss, int se, int[] arr) { int n = arr.length; if (ss<0 || se > n-1 || ss>se) throw new IllegalArgumentException("Invalid arguments"); return findGcd(0, n-1, ss, se, 0); } /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[si] qs & qe --> Starting and ending indexes of query range */ public static int findGcd(int ss, int se, int qs, int qe, int si) { if (ss>qe || se < qs) return 0; if (qs<=ss && qe>=se) return st[si]; int mid = ss+(se-ss)/2; return gcd(findGcd(ss, mid, qs, qe, si*2+1), findGcd(mid+1, se, qs, qe, si*2+2)); } // Driver Code public static void main(String[] args)throws IOException { int[] a = {2, 3, 6, 9, 5}; constructSegmentTree(a); int l = 1; // Starting index of range. int r = 3; //Last index of range. System.out.print("GCD of the given range is: "); System.out.print(findRangeGcd(l, r, a)); } }

Output:

GCD of the given range is: 3

**Time Complexity:** Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction. Time complexity to query is O(Log n). To query a range GCD, we process at most two nodes at every level and number of levels is O(Logn).

This article is contributed by **Nikhil Tekwani**. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.