Minimum LCM of all pairs in a given array

Given an array arr[] of size N, the task is to find the minimum LCM (Least Common Multiple) of all unique pairs in the given array, where 1 <= N <= 105, 1 <= arr[i] <= 105.

Examples:

Input: arr[] = {2, 4, 3}
Output: 4
Expalanation
LCM (2, 4) = 4
LCM (2, 3) = 6
LCM (4, 3) = 12
Minimum possible LCM is 4.

Input: arr [] ={1, 5, 2, 2, 6}
Output: 2

Naive Approach



  1. Generate all possible pairs and compute LCM for every unique pairs.
  2. Find the minimum LCM from all unique pairs.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find
// minimum possible lcm
// from any pair
  
#include <bits/stdc++.h>
using namespace std;
  
// function to compute
// GCD of two numbers
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
  
// function that return
// minimum possible lcm
// from any pair
int minLCM(int arr[], int n)
{
    int ans = INT_MAX;
    for (int i = 0; i < n; i++) {
  
        // fix the ith element and
        // iterate over all the array
        // to find minimum LCM
        for (int j = i + 1; j < n; j++) {
  
            int g = gcd(arr[i], arr[j]);
            int lcm = arr[i] / g * arr[j];
            ans = min(ans, lcm);
        }
    }
  
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = { 2, 4, 3, 6, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << minLCM(arr, n) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find minimum
// possible lcm from any pair
import java.io.*; 
import java.util.*; 
  
class GFG { 
      
// Function to compute
// GCD of two numbers
static int gcd(int a, int b)
    if (b == 0)
        return a;
    return gcd(b, a % b);
  
// Function that return minimum
// possible lcm from any pair
static int minLCM(int arr[], int n)
{
    int ans = Integer.MAX_VALUE;
      
    for(int i = 0; i < n; i++) 
    {
          
       // Fix the ith element and
       // iterate over all the array
       // to find minimum LCM
       for(int j = i + 1; j < n; j++) 
       {
          int g = gcd(arr[i], arr[j]);
          int lcm = arr[i] / g * arr[j];
          ans = Math.min(ans, lcm);
       }
    }
    return ans;
}
      
// Driver code 
public static void main(String[] args) 
    int arr[] = { 2, 4, 3, 6, 5 };
    int n = arr.length;
      
    System.out.println(minLCM(arr,n)); 
  
// This code is contributed by coder001

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find minimum 
# possible lcm from any pair 
import sys
  
# Function to compute 
# GCD of two numbers 
def gcd(a, b):
      
    if (b == 0):
        return a;
    return gcd(b, a % b);
  
# Function that return minimum 
# possible lcm from any pair
def minLCM(arr, n):
      
    ans = 1000000000;
    for i in range(n):
  
        # Fix the ith element and 
        # iterate over all the 
        # array to find minimum LCM
        for j in range(i + 1, n):
              
            g = gcd(arr[i], arr[j]);
            lcm = arr[i] / g * arr[j];
            ans = min(ans, lcm);
              
    return ans;
  
# Driver code
arr = [ 2, 4, 3, 6, 5 ];
  
print(minLCM(arr, 5))
  
# This code is contributed by grand_master

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find minimum
// possible lcm from any pair
using System;
class GFG{ 
      
// Function to compute
// GCD of two numbers
static int gcd(int a, int b)
    if (b == 0)
        return a;
    return gcd(b, a % b);
  
// Function that return minimum
// possible lcm from any pair
static int minLCM(int []arr, int n)
{
    int ans = Int32.MaxValue;
      
    for(int i = 0; i < n; i++) 
    {
          
    // Fix the ith element and
    // iterate over all the array
    // to find minimum LCM
    for(int j = i + 1; j < n; j++) 
    {
        int g = gcd(arr[i], arr[j]);
        int lcm = arr[i] / g * arr[j];
        ans = Math.Min(ans, lcm);
    }
    }
    return ans;
}
      
// Driver code 
public static void Main() 
    int []arr = { 2, 4, 3, 6, 5 };
    int n = arr.Length;
      
    Console.Write(minLCM(arr,n)); 
  
// This code is contributed by Akanksha_Rai

chevron_right


Output:

4

Time Complexity: O(N2)

Efficient Approach: This approach depends upon the formula:

Product of two number = LCM of two number * GCD of two number

  1. In the formula of LCM, the denominator is the GCD of two numbers, and GCD of two number will never be greater than the number itself.
  2. So for a fixed GCD, find the smallest two multiples of that fixed GCD that is present in the given array.
  3. Store only the smallest two multiples of each GCD because choosing a bigger multiple of GCD that is present in the array, no matter what, it will never give the minimum answer.
  4. Finally use sieve to find the minimum two number that is the multiple of the chosen GCD.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the
// pair having minimum LCM
  
#include <bits/stdc++.h>
using namespace std;
  
// function that return
// pair having minimum LCM
int minLCM(int arr[], int n)
{
    int mx = 0;
    for (int i = 0; i < n; i++) {
  
        // find max element in the array as
        // the gcd of two elements from the
        // array can't greater than max element.
        mx = max(mx, arr[i]);
    }
  
    // created a 2D array to store minimum
    // two multiple of any particular i.
    vector<vector<int> > mul(mx + 1);
  
    for (int i = 0; i < n; i++) {
        if (mul[arr[i]].size() > 1) {
            // we already found two
            // smallest multiple
            continue;
        }
        mul[arr[i]].push_back(arr[i]);
    }
  
    // iterating over all gcd
    for (int i = 1; i <= mx; i++) {
  
        // iterating over its multiple
        for (int j = i + i; j <= mx; j += i) {
  
            if (mul[i].size() > 1) {
  
                // if we already found the
                // two smallest multiple of i
                break;
            }
            for (int k : mul[j]) {
                if (mul[i].size() > 1)
                    break;
                mul[i].push_back(k);
            }
        }
    }
  
    int ans = INT_MAX;
    for (int i = 1; i <= mx; i++) {
  
        if (mul[i].size() <= 1)
            continue;
  
        // choosing smallest two multiple
        int a = mul[i][0], b = mul[i][1];
  
        // calculating lcm
        int lcm = (a * b) / i;
  
        ans = min(ans, lcm);
    }
  
    // return final answer
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = { 2, 4, 3, 6, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << minLCM(arr, n) << endl;
    return 0;
}

chevron_right


Output:

4

Time Complexity: O((N + M) * log(M))
Auxiliary Space: O(M) where M is the maximum element in the array

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.