We know, The above relation only holds for two numbers,
The idea here is to extend our relation for more than 2 numbers. Let’s say we have an array arr[] that contains n elements whose LCM needed to be calculated.
The main steps of our algorithm are:
Initialize ans = arr[0].
Iterate over all the elements of the array i.e. from i = 1 to i = n-1 At the ith iteration ans = LCM(arr[0], arr[1], …….., arr[i-1]). This can be done easily as LCM(arr[0], arr[1], …., arr[i]) = LCM(ans, arr[i]). Thus at i’th iteration we just have to do ans = LCM(ans, arr[i]) = ans x arr[i] / gcd(ans, arr[i])
Below is the implementation of the above algorithm :
Time Complexity: O(n * log(min(a, b))), where n represents the size of the given array. Auxiliary Space: O(n*log(min(a, b))) due to recursive stack space.
Below is the implementation of the above algorithm Recursively :
C++
#include <bits/stdc++.h>
usingnamespacestd;
//recursive implementation
intLcmOfArray(vector<int> arr, intidx){
// lcm(a,b) = (a*b/gcd(a,b))
if(idx == arr.size()-1){
returnarr[idx];
}
inta = arr[idx];
intb = LcmOfArray(arr, idx+1);
return(a*b/__gcd(a,b)); // __gcd(a,b) is inbuilt library function
}
intmain() {
vector<int> arr = {1,2,8,3};
cout << LcmOfArray(arr, 0) << "\n";
arr = {2,7,3,9,4};
cout << LcmOfArray(arr,0) << "\n";
return0;
}
Java
importjava.util.*;
importjava.io.*;
classGFG
{
// Recursive function to return gcd of a and b
staticint__gcd(inta, intb)
{
returnb == 0? a:__gcd(b, a % b);
}
// recursive implementation
staticintLcmOfArray(int[] arr, intidx)
{
// lcm(a,b) = (a*b/gcd(a,b))
if(idx == arr.length - 1){
returnarr[idx];
}
inta = arr[idx];
intb = LcmOfArray(arr, idx+1);
return(a*b/__gcd(a,b)); //
}
publicstaticvoidmain(String[] args)
{
int[] arr = {1,2,8,3};
System.out.print(LcmOfArray(arr, 0)+ "\n");
int[] arr1 = {2,7,3,9,4};
System.out.print(LcmOfArray(arr1,0)+ "\n");
}
}
// This code is contributed by gauravrajput1
Python3
def__gcd(a, b):
if(a ==0):
returnb
return__gcd(b %a, a)
# recursive implementation
defLcmOfArray(arr, idx):
# lcm(a,b) = (a*b/gcd(a,b))
if(idx ==len(arr)-1):
returnarr[idx]
a =arr[idx]
b =LcmOfArray(arr, idx+1)
returnint(a*b/__gcd(a,b)) # __gcd(a,b) is inbuilt library function
arr =[1,2,8,3]
print(LcmOfArray(arr, 0))
arr =[2,7,3,9,4]
print(LcmOfArray(arr,0))
# This code is contributed by divyeshrabadiya07.
C#
usingSystem;
classGFG {
// Function to return
// gcd of a and b
staticint__gcd(inta, intb)
{
if(a == 0)
returnb;
return__gcd(b % a, a);
}
//recursive implementation
staticintLcmOfArray(int[] arr, intidx){
// lcm(a,b) = (a*b/gcd(a,b))
if(idx == arr.Length-1){
returnarr[idx];
}
inta = arr[idx];
intb = LcmOfArray(arr, idx+1);
return(a*b/__gcd(a,b)); // __gcd(a,b) is inbuilt library function
}
staticvoidMain() {
int[] arr = {1,2,8,3};
Console.WriteLine(LcmOfArray(arr, 0));
int[] arr1 = {2,7,3,9,4};
Console.WriteLine(LcmOfArray(arr1,0));
}
}
Javascript
<script>
// Function to return
// gcd of a and b
function__gcd(a, b)
{
if(a == 0)
returnb;
return__gcd(b % a, a);
}
//recursive implementation
functionLcmOfArray(arr, idx){
// lcm(a,b) = (a*b/gcd(a,b))
if(idx == arr.length-1){
returnarr[idx];
}
let a = arr[idx];
let b = LcmOfArray(arr, idx+1);
return(a*b/__gcd(a,b)); // __gcd(a,b) is inbuilt library function
}
let arr = [1,2,8,3];
document.write(LcmOfArray(arr, 0) + "</br>");
arr = [2,7,3,9,4];
document.write(LcmOfArray(arr,0));
// This code is contributed by decode2207.
</script>
Output
24
252
Time Complexity: O(n * log(max(a, b)), where n represents the size of the given array. Auxiliary Space: O(n) due to recursive stack space.
Method 3: This code uses the reduce function from the functools library and the gcd function from the math library to find the LCM of a list of numbers. The reduce function applies the lambda function to the elements of the list, cumulatively reducing the list to a single value (the LCM in this case). The lambda function calculates the LCM of two numbers using the same approach as the previous implementation. The final LCM is returned as the result.
returnreduce(lambdax, y: x *y //math.gcd(x, y), numbers, 1)
numbers =[2, 3, 4, 5]
print("LCM of", numbers, "is", lcm(numbers))
C#
usingSystem;
usingSystem.Linq;
classProgram
{
staticintLcm(int[] numbers)
{
returnnumbers.Aggregate((x, y) => x * y / Gcd(x, y));
}
staticintGcd(inta, intb)
{
if(b == 0)
returna;
returnGcd(b, a % b);
}
staticvoidMain()
{
int[] numbers = { 2, 3, 4, 5 };
intlcm = Lcm(numbers);
Console.WriteLine("LCM of {0} is {1}", string.Join(", ", numbers), lcm);
}
}
Javascript
functionlcm(numbers) {
functiongcd(a, b) {
// If the second argument is 0, return the first argument (base case)
if(b === 0) {
returna;
}
// Otherwise, recursively call gcd with arguments b and the remainder of a divided by b
returngcd(b, a % b);
}
// Reduce the array of numbers by multiplying each number together and dividing by their gcd
// This finds the Least Common Multiple (LCM) of the numbers in the array
returnnumbers.reduce((a, b) => a * b / gcd(a, b));
}
// array
let numbers = [2, 3, 4, 5];
// Call the lcm function
let lcmValue = lcm(numbers);
// Print the Output
console.log(`LCM of ${numbers.join(', ')} is ${lcmValue}`);
Output
LCM of 4 numbers is 60
The time complexity of the program is O(n log n)
The auxiliary space used by the program is O(1)
Method 4: Using Euclidean algorithm
The function starts by initializing the lcm variable to the first element in the array. It then iterates through the rest of the array, and for each element, it calculates the GCD of the current lcm and the element using the Euclidean algorithm. The calculated GCD is stored in the gcd variable.
Once the GCD is calculated, the LCM is updated by multiplying the current lcm with the element and dividing by the GCD. This is done using the formula LCM(a,b) = (a * b) / GCD(a,b).
The time complexity of the above code is O(n log n), where n is the length of the input array. This is because for each element of the array, we need to find the GCD, which has a time complexity of O(log n) using the Euclidean algorithm. Since we are iterating over n elements of the array, the overall time complexity becomes O(n log n).
The auxiliary space used by this algorithm is O(1), as only a constant number of variables are used throughout the algorithm, regardless of the size of the input array.
This article is contributed by Madhur Modi. If you like neveropen and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!