Open In App
Related Articles

C++ Program to Find the GCDs of given index ranges in an array

Improve Article
Save Article
Like Article

Write a C++ program for a given array a[0 . . . n-1], the task is to find the GCD from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1.


Input: arr[] = {2, 3, 60, 90, 50};
Index Ranges: {1, 3}, {2, 4}, {0, 2}
Output: GCDs of given ranges are 3, 10, 1
Explanation: Elements in the range [1, 3] are {3, 60, 90}.
The GCD of the numbers is 3.
Elements in the range [2, 4] are {60, 90, 50}.
The GCD of the numbers is 10.
Elements in the range [0, 2] are {2, 3, 60}.
The GCD of the numbers is 1 as 2 and 3 are co-prime.

C++ Program to Find the GCDs of given index ranges in an array using Naive Approach:

A simple solution is to run a loop from qs to qe for every query and find GCD in the given range. Time required to find gcd of all the elements from qs to qe will be O(N*log(Ai)) i.e do a linear scan and find the gcd of each adjacent pair in O(log(Ai))

Time Complexity: O(Q*N*log(Ai))
Auxiliary Space: O(1)

C++ Program to Find the GCDs of given index ranges using 2D Array:

Another approach is to create a 2D array where an entry [i, j] stores the GCD of elements in range arr[i . . . j]. GCD of a given range can now be calculated in O(1) time. 

Time Complexity: O(N2 + Q) preprocessing takes O(N2) time and O(Q) time to answer Q queries.
Auxiliary Space: O(N2)

C++ Program to Find the GCDs of given index ranges using Segment Tree:

Prerequisites: Segment Tree Set 1Segment Tree Set 2 

Segment tree can be used to do preprocessing and query in moderate time. With a segment tree, we can store the GCD of a segment and use that later on for calculating the GCD of given range. 

This can be divided into the following steps:

Representation of Segment tree

  • Leaf Nodes are the elements of the input array.
  • Each internal node represents the GCD of all leaves under it.
  • Array representation of the tree is used to represent Segment Trees i.e., for each node at index i,
    • The 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 the given array

  • Begin with a segment arr[0 . . . n-1] and keep dividing into two halves (if it has not yet become a segment of length 1), 
    • Call the same procedure on both halves,.
      • Each parent node will store the value of GCD(left node, right node).

Query for GCD of given range

  • For every query, move to the left and right halves of the tree. 
    • Whenever the given range completely overlaps any halve of a tree, return the node from that half without traversing further in that region. 
    • When a halve of the tree completely lies outside the given range, return 0 (as GCD(0, x) = x). 
    • On partial overlapping of range, traverse in left and right halves and return accordingly.

Below is the implementation of the above approach:


// 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;
/* 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[]. 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;
        = __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;


GCD of the given range is:3

Time complexity: O(N * log(min(a, b))), where N is the number of modes and a and b are nodes whose GCD is calculated during the merge operation.
Auxiliary space: O(N)

Please refer complete article on GCDs of given index ranges in an array for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 18 Oct, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials