Open In App

GCDs of given index ranges in an Array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N and Q queries of type {qs, qe} where qs and qe denote the starting and ending index of the query, the task is to find the GCD of all the numbers in the range.

Examples:

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.

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))
So, the overall time complexity will be O(Q*N*log(Ai)).

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

GCD of Range 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)

GCD of range using 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 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++




// 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[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));
    }
}


Python3




import math
 
# To store segment tree
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
def findGcd(ss, se, qs, qe, si):
    if ss > qe or se < qs:
        return 0
    if qs <= ss and qe >= se:
        return st[si]
    mid = ss + (se - ss) // 2
    return math.gcd(findGcd(ss, mid, qs, qe, si * 2 + 1),
                    findGcd(mid + 1, se, qs, qe, si * 2 + 2))
 
# Finding the gcd of given range
def findRangeGcd(ss, se, arr, n):
    if ss < 0 or se > n - 1 or ss > se:
        print("Invalid Arguments")
        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
def constructST(arr, ss, se, si):
    if ss == se:
        st[si] = arr[ss]
        return st[si]
    mid = ss + (se - ss) // 2
    st[si] = math.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
def constructSegmentTree(arr, n):
    height = math.ceil(math.log2(n))
    size = 2 * pow(2, height) - 1
    global st
    st = [0] * size
    constructST(arr, 0, n - 1, 0)
    return st
 
# Driver program to test above functions
a = [2, 3, 6, 9, 5]
n = len(a)
 
# Build segment tree from given array
constructSegmentTree(a, n)
 
# Starting index of range. These indexes are 0 based.
l = 1
 
# Last index of range. These indexes are 0 based.
r = 3
 
print("GCD of the given range is:", findRangeGcd(l, r, a, n))


C#




// C# Program to find GCD of a number in a given Range
// using segment Trees
using System;
 
class GFG {
    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.Ceiling(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) {
            Console.WriteLine("Invalid arguments");
            return int.MinValue;
        }
 
        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)
    {
        int[] a = { 2, 3, 6, 9, 5 };
 
        constructSegmentTree(a);
 
        int l = 1; // Starting index of range.
        int r = 3; // Last index of range.
        Console.Write("GCD of the given range is: ");
        Console.Write(findRangeGcd(l, r, a));
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
// Javascript Program to find GCD of a number in a given Range
// using segment Trees
let 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 */
function constructSegmentTree(arr) {
    let height = Math.floor(Math.ceil(Math.log(arr.length) / Math.log(2)));
    let size = 2 * Math.pow(2, height) - 1;
    st = new Array(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
function constructST(arr, ss, se, si) {
    if (ss == se) {
        st[si] = arr[ss];
        return st[si];
    }
    let mid = Math.floor(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.
function gcd(a, b) {
    if (a < b) {
        // If b greater than a swap a and b
        let temp = b;
        b = a;
        a = temp;
    }
 
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
//Finding The gcd of given Range
function findRangeGcd(ss, se, arr) {
    let n = arr.length;
 
    if (ss < 0 || se > n - 1 || ss > se)
        throw new Error("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 */
function findGcd(ss, se, qs, qe, si) {
    if (ss > qe || se < qs)
        return 0;
 
    if (qs <= ss && qe >= se)
        return st[si];
 
    let mid = Math.floor(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
 
let a = [2, 3, 6, 9, 5]
 
constructSegmentTree(a);
 
let l = 1; // Starting index of range.
let r = 3; //Last index of range.
document.write("GCD of the given range is: ");
document.write(findRangeGcd(l, r, a));
 
// This code is contributed by saurabh_jaiswaal.
</script>


Output:

 GCD of the given range is: 3

Time Complexity: 

  • Time Complexity for tree construction is 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. 
  • Time complexity for each to query is O(log N * log(min(a, b)))

Auxiliary Space: O(N)



Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads