![]() |
VOOZH | about |
Given an array of positive integers, find LCM of the elements present in array.
Examples:
Input : arr[] = {1, 2, 3, 4, 28}
Output : 84
Input : arr[] = {4, 6, 12, 24, 30}
Output : 120
We have discussed LCM of array using GCD.
In this post a different approach is discussed that doesn't require computation of GCD. Below are steps.
Illustration :
Let we have to find the LCM of
arr[] = {1, 2, 3, 4, 28}
We initialize result = 1.
2 is a common factor that appears in
two or more elements. We divide all
multiples by two and multiply result
with 2.
arr[] = {1, 1, 3, 2, 14}
result = 2
2 is again a common factor that appears
in two or more elements. We divide all
multiples by two and multiply result
with 2.
arr[] = {1, 1, 3, 1, 7}
result = 4
Now there is no common factor that appears
in two or more array elements. We multiply
all modified array elements with result, we
get.
result = 4 * 1 * 1 * 3 * 1 * 7
= 84
Below is the implementation of above algorithm.
Output:
420
Time Complexity: O(max * n), where n represents the size of the given array and m represents the maximum element present in the array.
Auxiliary Space: O(n), where n represents the size of the given array.