Find the GCD of LCM of all unique pairs in an Array
Last Updated :
10 Apr, 2023
Given an integer array arr[] of size N, the task is to find the GCD of LCM of all unique pair (i, j) of the array, such that i < j.
Examples:
Input: arr[] = {10, 24, 40, 80}
Output: 40
Explanation:
LCM of all unique pairs following given conditions are:
LCM(10, 24) = 120
LCM(10, 40) = 40
LCM(10, 80) = 80
LCM(24, 40) = 120
LCM(24, 80) = 240
LCM(40, 80) = 80
Therefore, GCD of these LCM = GCD(120, 40, 80, 120, 240, 80) = 40
Input: arr[] = {1, 1}
Output: 1
Naive Approach: The simplest approach is the find all unique pairs in the array. Then find their LCM. Then find the GCD of all the LCM.
Efficient Approach: The above naive approach can be optimised with the help of Suffix array. We can use the Suffix array to find the LCM of each element paired with other elements, efficiently. Then we can simply find and return the GCD of this LCM array.
- For every element A[i], we need to calculate LCM(a[i], a[j]), where j belong to [i+1, N-1].
- LCM of all pairs where starting element is A[i] can be written as
LCM(A[i], GCD(all j in range i+1 to n-1))
- For that we build a suffix array. Let say suffix[] that stores the gcd of elements that belong to the range [i+1, N-1].
- Then create a LCM array to store the LCM of A[i] and GCD of all elements after it, i.e.
LCM[i] = LCM(A[i], suffix[i+1])
Where suffix[i+1] stores the GCD of elements [i+1, n-1]
- Finally compute the GCD of all elements in LCM array.
C++
// C++ code to find the GCD of LCM
// of all unique pairs in an Array
#include <bits/stdc++.h>
using namespace std;
// Find lcm of element x and y
int LCM(int x, int y)
{
return x * y / __gcd(x, y);
}
// Function that finds gcd of lcm
// of all pairs of elements.
void gcd_of_lcm(int n, int arr[])
{
// n is the size of the array.
// arr is the array.
// Suffix array that stores
// the gcd of the array elements.
int suff[n];
// Initialize suffix array.
for(int x = 0; x < n; x++)
{
suff[x] = 1;
}
// Loop that make the suffix gcd array
suff[n - 1] = arr[n - 1];
for(int i = n - 2; i >= 0; i--)
{
suff[i] = __gcd(arr[i], suff[i + 1]);
}
// lcm array that store the lcm
// of ith elements for all j
// that satisfy given condition.
vector<int> lcm;
for(int i = 0; i < n - 1; i++)
{
// we find lcm[i] for lcm
// of ith elements for all j
// using below formula.
int y = LCM(arr[i], suff[i + 1]);
// Add lcm of ith elements
// for all j in lcm array.
lcm.push_back(y);
}
// Now we find gcd of all ith elements.
// where i = 0, 1, 2, 3.....n-2.
int ans = lcm[0];
for(int i = 1; i < n - 1; i++)
{
ans = __gcd(ans, lcm[i]);
}
cout << ans << endl;
}
// Driver code
int main()
{
int n = 4;
int a[] = { 10, 24, 40, 80 };
// Function call for input 1
gcd_of_lcm(n, a);
n = 10;
int b[] = { 540, 648, 810, 648, 720,
540, 594, 864, 972, 648 };
// Function call for input 2
gcd_of_lcm(n, b);
}
// This code is contributed by shobhitgupta907
Java
// Java code to find the GCD of LCM
// of all unique pairs in an array
class GFG{
// Function to evaluate GCD of x and y
static int gcd(int x, int y)
{
if (y == 0)
return x;
else
return gcd(y, x % y);
}
// Function that finds gcd of lcm
// of all pairs of elements.
static void gcd_of_lcm(int n, int arr[])
{
// n = size of array i.e. arr[]
// Suffix array that stores
// the GCD of the array elements.
int suff[] = new int[n];
// Initialise the suffix array
for(int i = 0; i < n; i++)
suff[i] = 1;
// Loop that make suffix GCD array
suff[n - 1] = arr[n - 1];
for(int i = n - 2; i >= 0; i--)
suff[i] = gcd(arr[i], suff[i + 1]);
// lcm array that store lcm for pairwise
// consecutive elements
int lcm[] = new int[n - 1];
for(int i = 0; i < n - 1; i++)
// Find LCM using standard known formula
lcm[i] = (arr[i] * suff[i + 1]) /
gcd(arr[i], suff[i + 1]);
// Now we find gcd of all ith elements.
// where i = 0, 1, 2, 3.....n-2.
int ans = lcm[0];
for(int i = 1; i < n - 1; i++)
{
ans = gcd(ans, lcm[i]);
}
// Print the answer
System.out.println(ans);
}
// Driver code
public static void main(String[] args)
{
// 1st input case
int n = 4;
int a[] = { 10, 24, 40, 80 };
// Function call for input 1
gcd_of_lcm(n, a);
// 2nd input case
n = 10;
int b[] = { 540, 648, 810, 648, 720,
540, 594, 864, 972, 648 };
// Function call for input 2
gcd_of_lcm(n, b);
}
}
// This code is contributed by Soumitri Chattopadhyay
Python3
# Python3 code to find the GCD of LCM
# of all unique pairs in an Array
from math import gcd
# find lcm of element x and y
def LCM(x, y):
return (x * y)//gcd(x, y)
# Function that finds gcd of lcm
# of all pairs of elements.
def gcd_of_lcm(n, arr):
# n is the size of the array.
# arr is the array.
# suffix array that stores
# the gcd of the array elements.
suff = [1]*n
# initialize suffix array.
# loop that make the suffix gcd array.
suff[n-1] = arr[n-1]
for i in range(n-2, -1, -1):
suff[i] = gcd(arr[i], suff[i + 1])
# lcm array that store the lcm
# of ith elements for all j
# that satisfy given condition.
lcm = []
for i in range(n-1):
# we find lcm[i] for lcm
# of ith elements for all j
# using below formula.
y = LCM( arr[i], suff[i + 1])
# add lcm of ith elements
# for all j in lcm array.
lcm.append(y)
# now we find gcd of all ith elements.
# where i = 0, 1, 2, 3.....n-2.
ans = lcm[0]
for i in range(1, n-1):
ans = gcd(ans, lcm[i])
print(ans)
if __name__== "__main__":
n = 4
a =[10, 24, 40, 80]
# function call for input 1
gcd_of_lcm(n, a)
n = 10
a =[540, 648, 810, 648, 720,
540, 594, 864, 972, 648]
# function call for input 2
gcd_of_lcm(n, a)
C#
// C# code to find the GCD of LCM
// of all unique pairs in an array
using System;
class GFG{
// Function to evaluate GCD of x and y
static int gcd(int x, int y)
{
if (y == 0)
return x;
else
return gcd(y, x % y);
}
// Function that finds gcd of lcm
// of all pairs of elements.
static void gcd_of_lcm(int n, int[] arr)
{
// n = size of array i.e. arr[]
// Suffix array that stores
// the GCD of the array elements.
int[] suff = new int[n];
// Initialise the suffix array
for(int i = 0; i < n; i++)
suff[i] = 1;
// Loop that make suffix GCD array
suff[n - 1] = arr[n - 1];
for(int i = n - 2; i >= 0; i--)
suff[i] = gcd(arr[i], suff[i + 1]);
// lcm array that store lcm for pairwise
// consecutive elements
int[] lcm = new int[n - 1];
for(int i = 0; i < n - 1; i++)
// Find LCM using standard known formula
lcm[i] = (arr[i] * suff[i + 1]) /
gcd(arr[i], suff[i + 1]);
// Now we find gcd of all ith elements.
// where i = 0, 1, 2, 3.....n-2.
int ans = lcm[0];
for(int i = 1; i < n - 1; i++)
{
ans = gcd(ans, lcm[i]);
}
// Print the answer
Console.WriteLine(ans);
}
// Driver code
public static void Main()
{
// 1st input case
int n = 4;
int[] a = { 10, 24, 40, 80 };
// Function call for input 1
gcd_of_lcm(n, a);
// 2nd input case
n = 10;
int[] b = { 540, 648, 810, 648, 720,
540, 594, 864, 972, 648 };
// Function call for input 2
gcd_of_lcm(n, b);
}
}
// This code is contributed by sanjoy_62
JavaScript
<script>
// Javascript code to find the GCD of LCM
// of all unique pairs in an array
// Function to evaluate GCD of x and y
function gcd(x, y)
{
if (y == 0)
return x;
else
return gcd(y, x % y);
}
// Function that finds gcd of lcm
// of all pairs of elements.
function gcd_of_lcm(n, arr)
{
// n = size of array i.e. arr[]
// Suffix array that stores
// the GCD of the array elements.
let suff = new Array(n);
// Initialise the suffix array
for(let i = 0; i < n; i++)
suff[i] = 1;
// Loop that make suffix GCD array
suff[n - 1] = arr[n - 1];
for(let i = n - 2; i >= 0; i--)
suff[i] = gcd(arr[i], suff[i + 1]);
// lcm array that store lcm for pairwise
// consecutive elements
let lcm = new Array(n - 1);
for(let i = 0; i < n - 1; i++)
// Find LCM using standard known formula
lcm[i] = parseInt((arr[i] * suff[i + 1]) /
gcd(arr[i], suff[i + 1]), 10);
// Now we find gcd of all ith elements.
// where i = 0, 1, 2, 3.....n-2.
let ans = lcm[0];
for(let i = 1; i < n - 1; i++)
{
ans = gcd(ans, lcm[i]);
}
// Print the answer
document.write(ans + "</br>");
}
// Driver code
// 1st input case
let n = 4;
let a = [ 10, 24, 40, 80 ];
// Function call for input 1
gcd_of_lcm(n, a);
// 2nd input case
n = 10;
let b = [ 540, 648, 810, 648, 720,
540, 594, 864, 972, 648 ];
// Function call for input 2
gcd_of_lcm(n, b);
// This code is contributed by rameshtravel07
</script>
Time Complexity: O(N * log M), where M is the maximum element in the array.
Space Complexity: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read