![]() |
VOOZH | about |
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)
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)
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:
Below is the implementation of the above approach.
Output:
GCD of the given range is: 3
Time Complexity:
Auxiliary Space: O(N)