Java Program to Find the GCDs of given index ranges in an array
Last Updated :
18 Oct, 2023
Write a Java 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.
Example:
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.
Java 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)
Java 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)
Java Program to Find the GCDs of given index ranges 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:
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));
}
}
OutputGCD 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!
Similar Reads
Queries to update a given index and find gcd in range Given an array arr[] of N integers and queries Q. Queries are of two types: Update a given index ind by X.Find the gcd of the elements in the index range [L, R]. Examples: Input: arr[] = {1, 3, 6, 9, 9, 11} Type 2 query: L = 1, R = 3 Type 1 query: ind = 1, X = 10 Type 2 query: L = 1, R = 3 Output: 3
15+ min read
Find the array B[] from A[] according to the given conditions Given an array X[] of length N, having all elements less than or equal to M, the task is to print an array let's say Y[] of the same length following the given conditions: Prefix GCD till index i in Y[] must be equal to ith element of X[] for all i (0 <= i <= N-1)The output array must be lexog
8 min read
Queries for GCD of all numbers of an array except elements in a given range Given an array of n numbers and a number of queries are also given. Each query will be represented by two integers l, r. The task is to find out the GCD of all the numbers of the array excluding the numbers given in the range l, r (both inclusive) for each query.Examples: Input : arr[] = {2, 6, 9} R
10 min read
Queries to calculate GCD of an array after multiplying first or last K elements by X Given an array arr[] consisting of N positive integers and a 2D array queries[][] of the type {a, K, X} such that if the value of a is 1, then multiply first K array elements by X. Otherwise, multiply last K array elements by X. The task is to calculate GCD of the array after performing each query o
10 min read
Count of distinct coprime pairs product of which divides all elements in index [L, R] for Q queries Given an array arr[] of N integers and Q queries of the form (l, r). The task is to find the number of distinct pairs of coprime integers for each query such that all integers in index range [l, r] are divisible by the product of the coprime integers. Examples: Input: arr[] = {1, 2, 2, 4, 5}, querie
15 min read
Smallest subarray with GCD as 1 | Segment Tree Given an array arr[], the task is to find the smallest sub-arrays with GCD equal to 1. If there is no such sub-array then print -1. Examples: Input: arr[] = {2, 6, 3} Output: 3 {2, 6, 3} is the only sub-array with GCD = 1. Input: arr[] = {2, 2, 2} Output: -1 Approach: This problem can be solved in O
10 min read