Finding LCM of more than two (or array) numbers without using GCD in C++

C++Server Side ProgrammingProgramming

We have an array A, we have to find the LCM of all elements without using the GCD operation. If the array is like {4, 6, 12, 24, 30}, then the LCM will be 120.

The LCM can be calculated easily for two numbers. We have to follow this algorithm to get the LCM.

getLCM(a, b)

begin
   if a > b, then m := a, otherwise m := b
      while true do
         if m is divisible by both a and b, then return m
            m := m + 1
   done
end

Use this function to get LCM of first two numbers of array, then result of LCM will be used to find LCM of next element, thus we can get the result

Example

 Live Demo

#include <iostream>
using namespace std;
int getLCM(int a, int b){
   int m;
   m = (a > b) ? a : b;
   while(true){
      if(m % a == 0 && m % b == 0)
      return m;
      m++;
   }
}
int getLCMArray(int arr[], int n){
   int lcm = getLCM(arr[0], arr[1]);
   for(int i = 2; i < n; i++){
      lcm = getLCM(lcm, arr[i]);
   }
   return lcm;
}
int main() {
   int arr[] = {4, 6, 12, 24, 30};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "LCM of array elements: " << getLCMArray(arr, n);
}

Output

LCM of array elements: 120
raja
Published on 21-Oct-2019 17:20:57
Advertisements