Minimum LCM and GCD possible among all possible sub-arrays in C++

Suppose we have an array arr of size N. it has N positive numbers. We have to find the minimum elements of all possible subarray. Suppose the array is {2, 66, 14, 521}, then minimum LCM is 2, and GCD is 1.

We will solve this problem using a greedy approach. If we decrease the number of elements, then LCM will be less, and if we increase the array size, GCD will be less. We need to find the smallest element from the array, which is a single element, which will be required LCM. For GCD, GCD will be GCD of all elements of the array.


 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int minimum_gcd(int arr[], int n) {
   int GCD = 0;
   for (int i = 0; i < n; i++)
   GCD = __gcd(GCD, arr[i]);
   return GCD;
int minimum_lcm(int arr[], int n) {
   int LCM = arr[0];
   for (int i = 1; i < n; i++)
   LCM = min(LCM, arr[i]);
   return LCM;
int main() {
   int arr[] = { 2, 66, 14, 521 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "LCM: " << minimum_lcm(arr, n) << ", GCD: " << minimum_gcd(arr, n);


LCM: 2, GCD: 1

Updated on: 21-Oct-2019


Kickstart Your Career

Get certified by completing the course

Get Started