C++ Program for Range LCM Queries
Last Updated :
03 Jan, 2022
Given an array of integers, evaluate queries of the form LCM(l, r). There might be many queries, hence evaluate the queries efficiently.Â
Â
LCM (l, r) denotes the LCM of array elements
that lie between the index l and r
(inclusive of both indices)
Mathematically,
LCM(l, r) = LCM(arr[l], arr[l+1] , ......... ,
arr[r-1], arr[r])
Examples:Â
Â
Inputs : Array = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1, 44}
Queries: LCM(2, 5), LCM(5, 10), LCM(0, 10)
Outputs: 60 15708 78540
Explanation : In the first query LCM(5, 2, 10, 12) = 60,
similarly in other queries.
Â
A naive solution would be to traverse the array for every query and calculate the answer by using,Â
LCM(a, b) = (a*b) / GCD(a,b)
However as the number of queries can be large, this solution would be impractical.
An efficient solution would be to use segment tree. Recall that in this case, where no update is required, we can build the tree once and can use that repeatedly to answer the queries. Each node in the tree should store the LCM value for that particular segment and we can use the same formula as above to combine the segments. Hence we can answer each query efficiently!
Below is a solution for the same.Â
Â
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
int tree[4*MAX];
int arr[MAX];
int gcd( int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
int lcm( int a, int b)
{
return a*b/gcd(a,b);
}
void build( int node, int start, int end)
{
if (start==end)
{
tree[node] = arr[start];
return ;
}
int mid = (start+end)/2;
build(2*node, start, mid);
build(2*node+1, mid+1, end);
int left_lcm = tree[2*node];
int right_lcm = tree[2*node+1];
tree[node] = lcm(left_lcm, right_lcm);
}
int query( int node, int start, int end, int l, int r)
{
if (end<l || start>r)
return 1;
if (l<=start && r>=end)
return tree[node];
int mid = (start+end)/2;
int left_lcm = query(2*node, start, mid, l, r);
int right_lcm = query(2*node+1, mid+1, end, l, r);
return lcm(left_lcm, right_lcm);
}
int main()
{
arr[0] = 5;
arr[1] = 7;
arr[2] = 5;
arr[3] = 2;
arr[4] = 10;
arr[5] = 12;
arr[6] = 11;
arr[7] = 17;
arr[8] = 14;
arr[9] = 1;
arr[10] = 44;
build(1, 0, 10);
cout << query(1, 0, 10, 2, 5) << endl;
cout << query(1, 0, 10, 5, 10) << endl;
cout << query(1, 0, 10, 0, 10) << endl;
return 0;
}
|
Output:Â
Â
60
15708
78540
Please refer complete article on Range LCM Queries for more details!
Share your thoughts in the comments
Please Login to comment...